Shopware 6 - Tips, tricks and how to's

Accessing your plugin’s classes during its installation and activation

So you have created this awesome plugin, that you are so proud of. But for it to be perfect, you need to do some processes, when the plugin is being installed and activated. No problem, right? You simply go to the plugin’s main class, that resides in its src directory and use the standard methods like this:

This works nice and well, as long as you don’t need to use methods from some of your plugin’s classes. But what if you do? In that case, the first thing you would probably try, is the standard dependency injection. That is unfortunately not possible here, because the contructor of the main plugin’s class in final, which means, that you can’t change it. You can take a look at it yourself:

So without your custom constructor, there is no way of injecting the classes you need. Sure, you could instantiate them, using ‘new’. But that would be extremely tedious and impractical, because they probably have some dependencies and those dependencies have other dependencies. So what to do now?

Well, you could take a look at the class Bundle, which is a parent class of the Plugin class. There is a glimpse of hope here, because the $container is accessible from here. Container or more precisely the Service container, as the name suggests, is a magical box, that contains services. You can use it like this to basically simulate dependency injection, that you are used to use in the class constructors:

Victory? Unfortunately no. As you will find out, during plugin installation, your service (e.g. the class you want to inject and use its methods) is still not available. The reason for this is, that it is not contained in the Container, when you request it, because your plugin is not activated at that time. And here comes the whole point of this article: the solution.

How to add the plugin’s classes to the Service container

The Service container normally contains only some Shopware 6 core classes and repositories plus the classes of active plugins. So if we want to be able to access the classes of an inactive plugin, we need to add them to the container. For that, I have created a method, that you can put into your plugin’s main class and call it, whenever you need to access your plugin’s classes from there, even if the plugin is deactivated at the moment.

Simply put, it simulates, that your plugin is active and regenerates the container based on that. There is one more thing you need to do, before this can work. Go to the services.xml file, located in your Plugin’s src/Resources/config subdirectory and make your services public like this:

And that’s it! Now you are able to use whatever methods you have in any of your plugin’s classes. Took me a while to figure this out, so I hope it helps you. If you have an alternative solution or you simply want to thank me, please leave a comment below.