Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 30 ยท Getting Started

Your First Plugin

Build a minimal Shopware 6 plugin: composer.json, the Plugin base class, plugin:refresh, plugin:install --activate and a subscriber that says hello.

A Shopware plugin is smaller than most people expect. The smallest working plugin is a folder with two files: a composer.json that describes it and one PHP class that extends Shopware's Plugin base class. Everything else (services, templates, migrations, admin modules) is optional and added when you need it.

In this lesson you will create a plugin called AcmeHello, install it, and make it react to a page event by adding a greeting to the product page data. The real code is read-only here; the runnable part at the end is a stand-in plugin manager that shows what "refresh, install, activate" mean.

The folder

Plugins live in custom/plugins of your shop project. The folder name is the plugin name, and by convention it is the vendor prefix plus a descriptive name in StudlyCase:

TEXT
custom/plugins/AcmeHello/
  composer.json
  src/
    AcmeHello.php
    Resources/
      config/
        services.xml
    Subscriber/
      ProductPageSubscriber.php

The plugin name appears in many places: the folder, the main class name (by convention the same), the console commands and the prefix of configuration keys. Pick it once and keep it.

composer.json

Shopware reads plugin metadata from Composer's format. A minimal file looks like this:

JSON
{
  "name": "acme/hello",
  "description": "My first Shopware plugin",
  "type": "shopware-platform-plugin",
  "version": "1.0.0",
  "license": "proprietary",
  "authors": [
    { "name": "Acme Ltd" }
  ],
  "require": {
    "shopware/core": "~6.6.0"
  },
  "autoload": {
    "psr-4": {
      "Acme\\Hello\\": "src/"
    }
  },
  "extra": {
    "shopware-plugin-class": "Acme\\Hello\\AcmeHello",
    "label": {
      "en-GB": "Acme Hello",
      "de-DE": "Acme Hallo"
    },
    "description": {
      "en-GB": "Greets shoppers on the product page.",
      "de-DE": "Begruesst Kunden auf der Produktseite."
    }
  }
}

The important lines:

  • "type": "shopware-platform-plugin" marks the package as a Shopware plugin.
  • "extra.shopware-plugin-class" names the class Shopware should instantiate. Without it, the plugin is not found.
  • "autoload.psr-4" maps your namespace to src/, as in any Composer package. Plugins in custom/plugins are autoloaded by Shopware itself.
  • "require": { "shopware/core": ... } states which core versions the plugin supports. Use the version constraint that matches your shop; compatibility is covered in Packaging, Deployment and Updates.
  • "label" and "description" are what the administration shows in the plugin list. Provide en-GB and de-DE at least.

A mistake in composer.json (a missing shopware-plugin-class, or a namespace that does not match the folder structure) is the most common reason a plugin does not show up or crashes on install. Check the JSON syntax and the class name first.

The plugin class

PHP
<?php declare(strict_types=1);

namespace Acme\Hello;

use Shopware\Core\Framework\Plugin;

class AcmeHello extends Plugin
{
}

That is a complete plugin. The base class is a Symfony bundle, so Shopware boots it with the rest of the application. Overriding methods on it gives you the lifecycle hooks (install, update, activate and so on) that the next lessons cover in depth. For now, the empty class is enough.

Register it and turn it on

Shopware keeps a list of plugins in the database. You refresh the list so it notices your new folder, then install and activate:

Terminal
bin/console plugin:refresh
bin/console plugin:install --activate AcmeHello
bin/console cache:clear

Plugins have three states you will see in bin/console plugin:list: not installed, installed but inactive and installed and active. Installing runs the plugin's install code and migrations; activating makes it take part in requests (its services, subscribers and templates are only used while it is active). You can do both at once with --activate, as shown. To switch it off again, use plugin:deactivate, and to remove it, plugin:uninstall. The administration has an equivalent switch in Extensions, My extensions.

stateDiagram-v2
    [*] --> Discovered: plugin:refresh
    Discovered --> Installed: plugin:install
    Installed --> Active: plugin:activate
    Active --> Installed: plugin:deactivate
    Installed --> Discovered: plugin:uninstall

A plugin moves between discovered, installed and active; uninstalling returns it to discovered.

If the plugin does not appear after plugin:refresh, check the folder location, the JSON, the type and the plugin class name, in that order.

Your first behaviour: a subscriber

An event subscriber is the standard "hello world" because it needs no template or database. We want to attach a message to the product detail page. Shopware dispatches a page-loaded event after it builds the page object, and subscribers can add data to it.

First the subscriber class, src/Subscriber/ProductPageSubscriber.php:

PHP
<?php declare(strict_types=1);

namespace Acme\Hello\Subscriber;

use Shopware\Core\Framework\Struct\ArrayStruct;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class ProductPageSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            ProductPageLoadedEvent::class => 'onProductPageLoaded',
        ];
    }

    public function onProductPageLoaded(ProductPageLoadedEvent $event): void
    {
        $name = $event->getPage()->getProduct()->getTranslation('name');

        $event->getPage()->addExtension(
            'acmeHello',
            new ArrayStruct(['greeting' => 'Hello from Acme! You are looking at ' . $name])
        );
    }
}

An extension is a named box of extra data that a page, entity or other struct can carry without changing its class. A template can read page.extensions.acmeHello.greeting.

Then register it as a service with the event-subscriber tag in src/Resources/config/services.xml:

XML
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
    <services>
        <service id="Acme\Hello\Subscriber\ProductPageSubscriber">
            <tag name="kernel.event_subscriber"/>
        </service>
    </services>
</container>

Shopware loads Resources/config/services.xml from an active plugin automatically. After adding it, run bin/console cache:clear, open any product page and check the page data (for example, with the Symfony profiler in development, or by printing the extension in a template block). The next lessons explain services and Subscribers and Core Events properly.

A stand-in plugin manager

The real plugin manager reads Composer metadata, writes states to a database table, runs your lifecycle methods and boots the bundle. The stand-in below does the same in about forty lines, with a plain array as the "database". It lets you see why plugin:refresh must come before plugin:install, and why an inactive plugin does nothing.

PHP Refresh, install, activate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first attempt to install fails because the plugin was never discovered. After refresh the page is unchanged because nothing is active. Only after install and activate does the boot step register the listener.

A second stand-in parses a composer.json string and validates the fields Shopware needs, which is the check you perform by eye when a plugin does not show up.

PHP Validate plugin metadata

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Real: the metadata rules (type, plugin class, PSR-4 autoloading, labels). Stand-in: the checker itself, which Shopware does not ship in this form.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which composer.json field tells Shopware which class is the main plugin class?

    The shopware-plugin-class entry under extra names the class that Shopware instantiates; the type only marks the package as a plugin.
  2. 2. What does bin/console plugin:refresh do?

    It scans the plugin folders and updates Shopware's list of known plugins. You must run it before a new plugin can be installed.
  3. 3. Why is a subscriber registered with the kernel.event_subscriber tag?

    The tag lets Symfony's event dispatcher discover the service and register the events returned by getSubscribedEvents.
  4. 4. A plugin is installed but not active. What is true?

    Only active plugins take part in requests. Installation runs install code and migrations, but activation switches the plugin on.

Summary

  • The smallest plugin is a folder in custom/plugins with a composer.json and a class extending Shopware\Core\Framework\Plugin.
  • composer.json needs type: shopware-platform-plugin, PSR-4 autoloading and extra.shopware-plugin-class.
  • Use plugin:refresh, then plugin:install --activate, then cache:clear.
  • A subscriber tagged kernel.event_subscriber can add data to a page through an extension.
  • The plugin manager and the metadata checker in the TryIts are stand-ins that model the flow.

Next: Services and the Dependency Injection Container