Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 30 ยท Events, Flows and Background Work

Subscribers and Core Events

React to Shopware with event subscribers: EventSubscriberInterface, entity written and loaded events, page loaded events, priorities and how to avoid slow side effects.

Shopware announces nearly everything that happens: a product was written, a page finished loading, an order was placed. Your plugin can listen to these announcements without touching core code. The mechanism is Symfony's event dispatcher, so if you have not met it, read Events first. This lesson shows how Shopware uses it, which events matter most for plugins, and the habits that keep a listener from slowing down the whole shop.

A listener class is called a subscriber. It tells the dispatcher which events it wants and which method handles each one. Since Shopware cannot run on this site, the real code is read-only here. The runnable examples are stand-ins: a small dispatcher with priorities, and a comparison of a slow per-row subscriber against a batched one on SQLite.

A first subscriber

A subscriber implements Symfony\Component\EventDispatcher\EventSubscriberInterface and returns a map from event name to method in getSubscribedEvents():

PHP
<?php declare(strict_types=1);

namespace Acme\Badges\Subscriber;

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
    {
        $page = $event->getPage();
        // add data for the template here
    }
}

The method gets one argument: the event object. The object carries the data that the dispatcher wants to share, and many events let you change it. Register the subscriber in services.xml with the kernel.event_subscriber tag:

XML
<service id="Acme\Badges\Subscriber\ProductPageSubscriber">
    <tag name="kernel.event_subscriber"/>
</service>

After a cache clear the dispatcher knows about it. A subscriber that is not tagged simply never runs, which is the usual reason for "my event does nothing". The container details are in Services and the Dependency Injection Container.

The events you will use most

Shopware's events fall into a few families.

Entity events from the DAL

For every entity the DAL dispatches events named after the entity:

Event name Fires
product.loaded After products were read from the database
product.written After a product row was created or updated
product.deleted After a product was deleted
sales_channel.product.loaded After products were read for a sales channel (storefront and Store API)

The names follow the pattern <entity>.<action>, and the PHP constants live in classes such as Shopware\Core\Content\Product\ProductEvents. Your own entity gets the same events automatically, for example acme_vendor.written.

A written event gives you the ids and the write results:

PHP
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;

public static function getSubscribedEvents(): array
{
    return ['product.written' => 'onProductWritten'];
}

public function onProductWritten(EntityWrittenEvent $event): void
{
    $ids = $event->getIds();   // all product ids written by this operation
    // one call with many ids: work with the whole list, not one id at a time
}

A loaded event gives you the entities that were just read, so you can add data to them (EntityLoadedEvent::getEntities()). Keep in mind that a loaded event fires on every read, including category pages with dozens of products. Anything you do there is multiplied.

Page and request events

The storefront builds a page object for each route (product, listing, cart, checkout). When the page is ready, a "page loaded" event fires, for example ProductPageLoadedEvent or CheckoutConfirmPageLoadedEvent. The standard way to feed your own data into a Twig template is to add an extension to the page in a subscriber:

PHP
use Shopware\Core\Framework\Struct\ArrayStruct;

public function onProductPageLoaded(ProductPageLoadedEvent $event): void
{
    $product = $event->getPage()->getProduct();
    $event->getPage()->addExtension('acmeBadge', new ArrayStruct([
        'text' => $product->getCustomFields()['acme_badge_text'] ?? null,
    ]));
}

In Twig, the data is available as page.extensions.acmeBadge. Storefront Templates with Twig picks up from here.

Business events

Events such as CheckoutOrderPlacedEvent mark things that matter to the business: an order was placed, a customer registered, a payment state changed. These are also the triggers of the Flow Builder, which is the subject of Flow Builder: Triggers and Custom Actions. If you want your code to run when something happens in the shop and a merchant should be able to configure it, a flow action is often a better fit than a subscriber. If it is a technical reaction that must always happen, use a subscriber.

Priority

When several subscribers listen to one event, the dispatcher calls them from the highest priority number to the lowest. The default is 0. You can set a priority by returning an array instead of a method name:

PHP
return [
    ProductPageLoadedEvent::class => ['onProductPageLoaded', 100],
];

You can also list several methods for one event: [['first', 10], ['second', -10]]. Use priorities only when order truly matters, for example when your data depends on another subscriber's output. Relying on the accidental order of subscribers from different plugins is fragile.

sequenceDiagram
    participant C as Core code
    participant D as Event dispatcher
    participant A as Subscriber A (prio 100)
    participant B as Subscriber B (prio 0)
    C->>D: dispatch(ProductPageLoadedEvent)
    D->>A: onProductPageLoaded()
    A-->>D: done
    D->>B: onProductPageLoaded()
    B-->>D: done
    D-->>C: continue with the changed event

Subscribers run in priority order, each can modify the shared event object, and the core code continues afterward.

Performance and side effects

Subscribers run inside someone else's request, so they must be cheap and predictable. A few rules:

  • Never run a query per entity. A product.loaded subscriber that fetches one extra row for each of 40 products adds 40 queries to a category page. Collect the ids, run one query for all of them, and attach the results. This is the classic N+1 problem, shown below.
  • Do not do slow work inline. Sending mail, calling an external API or generating a file belongs in the message queue. A subscriber can dispatch a message and return at once.
  • Avoid side effects in read events. A loaded event may fire many times per request and in contexts you did not expect (Admin API, CLI, indexers). Writing data from a loaded event invites loops and surprises.
  • Check the context. If your logic is only for the storefront, use the page event and not the entity event. If it should skip system background work, look at the Context source.
  • Watch for loops. A product.written subscriber that writes a product triggers itself. Guard it with a condition or write through a path that does not dispatch the same event.
  • Handle failures. An exception in a subscriber travels up into the code that dispatched the event and can break checkout. Catch expected errors and log them.

Try it: a dispatcher with priorities

This stand-in is not Symfony's EventDispatcher, but it follows the same contract: subscribers return a map of event names to methods and priorities, and the dispatcher sorts by priority, highest first.

PHP Subscribers, priorities and a shared event

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 late subscriber sees the other two extensions because it runs last. Real code should not depend on that unless it sets the priority on purpose.

Try it: N+1 in a loaded event

A loaded event hands your subscriber a list. The cheap way and the costly way both give the same answer; the difference is the number of queries. This stand-in counts them on SQLite.

PHP Counting queries in a loaded-event subscriber

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.

On a real category page the same thing happens inside sales_channel.product.loaded: one query for the whole list keeps the page fast. In Shopware you would normally do the batching with a repository search using EqualsAnyFilter on the ids (see Reading and Writing with Repositories).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What makes the dispatcher know about your subscriber?

    Only tagged services are registered as subscribers. Without the tag the class never runs.
  2. 2. Which subscriber runs first?

    Higher numbers run first. The default priority is 0.
  3. 3. You need to attach a badge to the product page's Twig template. Which event is the usual place?

    The page loaded event lets you add an extension to the page object, which the template then reads.
  4. 4. Why is a database query per entity inside a loaded-event subscriber a problem?

    This is the N+1 problem. Collect the ids and fetch everything with one query.
  5. 5. Where should slow work such as sending a mail triggered by an event go?

    A subscriber runs inside someone else's request. Dispatch a message and let a worker do the slow part.

Summary

  • A subscriber implements EventSubscriberInterface, maps event names to methods, and is tagged kernel.event_subscriber.
  • The DAL dispatches <entity>.loaded, <entity>.written and <entity>.deleted for every entity, including your own.
  • Page loaded events are the standard way to pass extra data to Twig through page extensions.
  • Priorities decide the order, highest first; use them only when order matters.
  • Keep subscribers cheap: batch queries, avoid side effects in read events, guard against loops and move slow work to the queue.

Next, let merchants configure reactions in Flow Builder: Triggers and Custom Actions.