Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 30 ยท Architecture

Plugin Structure and Lifecycle

Understand the Shopware 6 plugin folder layout and the install, update, activate, deactivate and uninstall hooks, including keepUserData and update migrations.

A plugin is not just code that runs. It is something a merchant installs, switches on and off, updates to a new version and one day removes. Each of those moments is a chance to create data, move data or clean up, and Shopware gives you a hook for each. Getting the lifecycle right is what separates a plugin you can hand to a client from one that leaves tables behind or breaks on update.

This lesson covers the folder layout, the lifecycle methods on the Plugin class, the keepUserData flag, and how versions and migrations work together. Real code is read-only; a runnable state machine at the end models the allowed transitions.

A typical layout

Shopware looks for specific folders inside the plugin's src/ directory. A fuller version of the plugin from the last lesson might look like this:

TEXT
custom/plugins/AcmeBadges/
  composer.json
  CHANGELOG.md
  src/
    AcmeBadges.php                 main class (extends Plugin)
    Migration/                     database migrations
    Core/Content/Badge/            entities and definitions
    Service/                       your own services
    Subscriber/                    event subscribers
    Storefront/Controller/         storefront controllers
    Resources/
      config/
        services.xml               service definitions
        config.xml                 plugin settings
        routes.xml                 route imports
      views/storefront/            Twig templates
      snippet/                       translations
      app/
        administration/src/        Vue admin code
        storefront/src/            storefront JS and SCSS
      public/                      built assets

You do not need all of it. The point is that location carries meaning: Shopware finds Resources/config/services.xml, Resources/views, Migration/ and the app folders by convention, so keeping to the names avoids extra configuration. Subfolders like Core/Content/Badge just mirror how Shopware organises its own code and are a habit, not a rule.

The lifecycle methods

The Plugin base class defines empty methods that you override. Each receives a context object with information about the situation:

Method When it runs
install(InstallContext $context) When the plugin is installed, before it is marked installed
postInstall(InstallContext $context) After a successful installation
update(UpdateContext $context) When a new plugin version is installed over an old one
postUpdate(UpdateContext $context) After a successful update
activate(ActivateContext $context) When the plugin is switched on
deactivate(DeactivateContext $context) When the plugin is switched off
uninstall(UninstallContext $context) When the plugin is removed

All of the context classes live in Shopware\Core\Framework\Plugin\Context. A skeleton:

PHP
<?php declare(strict_types=1);

namespace Acme\Badges;

use Doctrine\DBAL\Connection;
use Shopware\Core\Framework\Plugin;
use Shopware\Core\Framework\Plugin\Context\ActivateContext;
use Shopware\Core\Framework\Plugin\Context\DeactivateContext;
use Shopware\Core\Framework\Plugin\Context\InstallContext;
use Shopware\Core\Framework\Plugin\Context\UninstallContext;
use Shopware\Core\Framework\Plugin\Context\UpdateContext;

class AcmeBadges extends Plugin
{
    public function install(InstallContext $context): void
    {
        // create default data that is not a table
    }

    public function update(UpdateContext $context): void
    {
        // data fixes that are not schema changes
    }

    public function activate(ActivateContext $context): void
    {
        // runs on every activation, so keep it idempotent
    }

    public function deactivate(DeactivateContext $context): void
    {
    }

    public function uninstall(UninstallContext $context): void
    {
        if ($context->keepUserData()) {
            return;
        }

        $connection = $this->container->get(Connection::class);
        $connection->executeStatement('DROP TABLE IF EXISTS `acme_badge`');
    }
}

The classic pattern is "install makes it, uninstall takes it away". Since activation can happen many times (a merchant may switch the plugin off and on), put work that must happen exactly once in install, and make activate safe to repeat.

Schema changes (creating or altering tables) normally belong in migrations, not in install. A migration is recorded and can be run again safely, while an install method runs once and cannot easily be repeated. The next chapter's Database Migrations lesson goes into detail. Use install for data, defaults and checks.

keepUserData

When a merchant uninstalls a plugin, the administration asks whether to keep or delete the plugin's data. The answer reaches your code as $context->keepUserData(). A typical rule:

  • If it is true, leave tables and custom fields alone. The merchant might reinstall later and expects the data to be there.
  • If it is false, remove everything your plugin created: tables, custom field sets, configuration values and any rows you added to core tables.

Never drop user data when keepUserData() is true, and never forget the cleanup when it is false. Orders, customers and products are not your plugin's data, so do not delete them even if your plugin extended them.

Also remember what deactivation should do: switch behaviour off, not destroy data. A deactivated plugin must leave the shop in a consistent state because merchants use deactivation as a quick way to rule out a plugin when something breaks.

Versions and update migrations

A plugin version is the version in composer.json, following semantic versioning. When the administration or console sees a higher version in the files than the installed one, an update is available. Running bin/console plugin:update AcmeBadges (or the admin button) performs these steps:

  1. The new version's files are in place.
  2. Shopware runs the plugin's migrations that are new since the last run.
  3. It calls your update() method, then postUpdate().
  4. It stores the new version number.
sequenceDiagram
    participant M as Merchant / CLI
    participant S as Shopware
    participant P as Your plugin
    M->>S: plugin:update
    S->>S: read new version from composer.json
    S->>P: run new migrations
    S->>P: update(UpdateContext)
    S->>P: postUpdate(UpdateContext)
    S-->>M: stored version = new version

An update runs migrations first, then your update hooks, and finally records the new version.

Inside update(), the context tells you which version you came from: $context->getCurrentPluginVersion() and $context->getUpdatePluginVersion() return the installed and the new version, and $context->getPlugin() gives the plugin entity. You can use version_compare to apply a fix only for installations older than a given version. Make every update step idempotent and tolerant of partially migrated data, because an update that fails halfway will be run again after you fix it.

A habit that saves trouble: write a changelog entry for each version, and never edit a migration that has already shipped. Add a new one instead.

A lifecycle state machine

The real transitions are enforced by Shopware, but modelling them is a good way to see which operations make sense in which state. The stand-in has four states and logs what the plugin's hooks would do, including the keepUserData choice on uninstall.

PHP Allowed lifecycle transitions

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.

In the first run the early uninstall is refused because the model requires deactivation first (the real tools may deactivate for you as part of uninstalling, so treat this as a simplification). In the second run the data survives, as it would when the merchant chooses to keep it.

The next stand-in applies update steps by version. Each step knows the version that introduced it, and the runner executes only the steps newer than the installed version, in order.

PHP Update steps by version

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 lifecycle methods, contexts and keepUserData. Stand-in: the transition table and the version runner (in Shopware, migrations track themselves by timestamp instead of semantic version).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which lifecycle method is best suited for work that must happen exactly once?

    Install runs once per installation, whereas activate can run many times if the plugin is switched off and on again.
  2. 2. What does UninstallContext::keepUserData() tell you?

    It reflects the merchant's choice in the uninstall dialog. When true you must not delete plugin data; when false you should clean up.
  3. 3. Where should a table creation normally live?

    Migrations are tracked and repeatable, which suits schema changes. Install hooks are for defaults and checks.
  4. 4. What is true about steps inside update()?

    If an update fails halfway it is rerun after the problem is fixed, so each step must tolerate being applied to partly updated data.
  5. 5. What should deactivation do?

    Merchants use deactivation to rule out a plugin, so it must leave the shop consistent and keep the data.

Summary

  • Shopware finds plugin parts by folder convention under src/ and Resources/.
  • Override install, update, activate, deactivate and uninstall (plus the post variants) on the Plugin class.
  • Use keepUserData() to decide whether uninstall removes the plugin's data; never touch core data such as orders.
  • Put schema changes in migrations, and make update steps idempotent.
  • An update runs new migrations, then update(), then postUpdate(), then stores the version.
  • The state machine and version runner are stand-ins that model the rules.

Next: Plugin Configuration