Search code examples
shopware

How to require a composer package inside a plugin?


I am coding a plugin for a Shopware 6 project which requires a composer package to validate barcodes and EANs.

I ran composer require imelgrat/barcode-validator inside my plugin folder. It adds the requirement to the composer.json but it also installs the package (and its requirements) directly inside the plugins vendor folder, which is wrong.

How can i require a composer package and install correct in the Shopware 6 vendor folder?


Solution

  • You can't. Not at the moment at least, if you distribute your plugin using zips. If you plan on distributing solely through composer, you can use the 'static-plugins' folder to install your plugin in your project through composer, which will also install the deps.

    Now, in case you want to distribute through the shopware store, you will have to supply the vendor folder in your plugin zip. You'll also have to actively include the autoloader in your plugin class.

    The following code snippet is placed above the class declaration of your plugin class, and loads the composer autoloader of the plugin - if it exists. This means you can still also distribute through composer, but also through a zip-file.

    if (file_exists(dirname(__DIR__) . '/vendor/autoload.php')) {
        $loader = require_once dirname(__DIR__) . '/vendor/autoload.php';
        if ($loader !== true) {
            spl_autoload_unregister([$loader, 'loadClass']);
            $loader->register(false);
        }
    }
    

    Example/source: https://github.com/runelaenen/shopware6-two-factor-auth/blob/master/src/RuneLaenenTwoFactorAuth.php

    On packaging your zip, don't forget to include the vendor folder, and you're ready to distribute your plugin.

    Do keep in mind though, that you cannot use a package twice in one system, class names have to be unique. So only include packages (and dependencies of them) that you are fairly certainly not used by core Shopware or other packages. Or use a tool like PHP Scoper to scope your plugin vendor folder so everything is always unique, even if it's already used in a system.


    Roadmap

    Shopware has composer integration on the roadmap, so this might soon be out of date. At time of writing (feb 2021) the above method is however the way to go.