How to reliably use a service from a Showpare 6 store plugin in my our plugin without issues

58 views Asked by At

We have installed a plugin from the Shopware 6 store via composer. For our own features, we want to use a service from the plugin.

Because plugins in shopware 6 can be uninstalled and/or deactivated, we can not reliably use the Service from the plugin in the services.xml in our own plugin/bundle. If the store plugin is still uninstalled/not activated, we get the error 'The service "..." has a dependency on a non-existent service'.

This example illustrates the situation:


    <services>
        <service id="MyPlugin..." public="true">
            <!-- Service might be uninstalled/inactive. Conditional?-->
            <argument type="service" id="ThirdPartyPlugin"/>
        </service>
    </services>

Are there any best practices, to handle this situation in Shopware? Can we implement a conditional that our service will be defined only if the 3rd party plugin is active?

1

There are 1 answers

1
j_elfering On BEST ANSWER

You can use on-invalid="null" when you wire the dependency, that way null gets injected instead of the real service if it is not present, your service then still has to handle what should happen in that case (e.g. early return, error message, etc), but at least the symfony container should boot up again.

Refer to the https://symfony.com/doc/current/service_container/optional_dependencies.html#setting-missing-dependencies-to-null for more information.

So for your example it should look like:

  <services>
        <service id="MyPlugin..." public="true">
            <!-- Service might be uninstalled/inactive. Null will be injected instead-->
            <argument type="service" id="ThirdPartyPlugin" on-invalid="null"/>
        </service>
    </services>