Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 30 ยท Architecture

Services and the Dependency Injection Container

Learn how Shopware plugins define services in services.xml, use tags, and decorate core services with the Symfony container, with a runnable mini container.

Nearly everything a plugin does is a service: a PHP object that does one job, gets what it needs handed to it, and is created by a container instead of by new. Subscribers, repositories, controllers, console commands and scheduled-task handlers are all services. Shopware uses Symfony's dependency injection container, so if you know Symfony you already know most of this lesson. If not, read Services and the Container and Service Tags first; here we focus on how Shopware applies them.

You will learn how to define a service in services.xml, what tags are for, how to decorate a core service (the safe way to change core behaviour), and how plugin services are loaded. A runnable stand-in container at the end shows decoration working.

Where services are defined

Shopware loads Resources/config/services.xml from every active plugin (the path is relative to the plugin's src/ folder, as in the previous lesson). XML is the style you will see in nearly all Shopware code and documentation, although the container also supports YAML and PHP configuration. A service definition names a class, its constructor arguments and optional tags:

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\Badges\Service\BadgeProvider">
            <argument type="service" id="product.repository"/>
            <argument type="service" id="Shopware\Core\System\SystemConfig\SystemConfigService"/>
            <argument type="service" id="logger"/>
        </service>
    </services>
</container>

The service id is conventionally the class name. Each <argument> is passed to the constructor in order. product.repository is the id of a repository the DAL registers for the product entity; you will use these repositories heavily in Reading and Writing with Repositories.

The class itself is plain PHP:

PHP
<?php declare(strict_types=1);

namespace Acme\Badges\Service;

use Psr\Log\LoggerInterface;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\System\SystemConfig\SystemConfigService;

class BadgeProvider
{
    public function __construct(
        private readonly EntityRepository $productRepository,
        private readonly SystemConfigService $config,
        private readonly LoggerInterface $logger,
    ) {
    }
}

Constructor injection makes dependencies visible and lets tests pass in fakes. Avoid asking the container for services at runtime (the "service locator" style): it hides what a class needs.

Autowiring

Symfony can guess constructor arguments from their type hints. You can switch this on with a <defaults autowire="true"/> element, and many plugins do. Shopware's own services, however, often have several implementations of the same interface or repositories that are distinguished only by id (such as product.repository and category.repository, which are both EntityRepository), and autowiring cannot choose between those by type. For that reason, explicit <argument> lines remain the most common and the most predictable style, and this track uses them.

Service lifecycle

By default services are created lazily the first time someone asks for them, then reused for the rest of the request. They are shared singletons within one container. Two consequences:

  • Do not keep request-specific state in a service property. In a normal web server each request starts a fresh PHP process state, but queue workers and long-running commands reuse services for thousands of jobs.
  • Services are private by default, which means you cannot fetch them from the container with get(). You receive them through constructors, which is the intended way. Set public="true" only for the few cases that need it, such as a service the framework looks up by id.

Tags

A tag is a label on a service that tells some other system "use me". The container itself does nothing with a tag; a compiler pass in the framework collects all services with a tag and wires them in. These are the tags you will meet most in plugin work:

Tag Meaning
kernel.event_subscriber Register the class as an event subscriber
console.command Make the class an available bin/console command
shopware.entity.definition Register a DAL entity definition
shopware.entity.extension Register a DAL entity extension
shopware.scheduled.task Register a scheduled task
messenger.message_handler Register a queue message handler
twig.extension Add Twig functions and filters

A tag can have attributes, for example <tag name="messenger.message_handler" handles="..."/>. Each later lesson names the tag it needs. If a class never reacts, a missing tag is the first thing to suspect.

flowchart LR
    X["services.xml<br/>tag: kernel.event_subscriber"] --> CP["Compiler pass<br/>collects tagged services"]
    CP --> D["Event dispatcher<br/>knows the subscriber"]
    D --> R["Request: event fired"]
    R --> S["Your handler runs"]

Tags are picked up while the container compiles, which is why cache:clear matters after changing them.

Decorating a core service

Sometimes you need to change what a core service does. Copying and rewriting it would break on the next update, and replacing it outright (an alias) can clash with another plugin. Decoration is the clean way: you wrap the original and delegate to it, adding behaviour before or after.

Many core services in Shopware are written for this. They are abstract classes with a getDecorated() method. You extend the abstract class, keep the original in a property, and call it inside the methods you change. Here is the shape of a decorator around the product price calculator:

PHP
<?php declare(strict_types=1);

namespace Acme\Badges\Service;

use Shopware\Core\Content\Product\SalesChannel\Price\AbstractProductPriceCalculator;
use Shopware\Core\System\SalesChannel\SalesChannelContext;

class LoggingPriceCalculator extends AbstractProductPriceCalculator
{
    public function __construct(private readonly AbstractProductPriceCalculator $inner)
    {
    }

    public function getDecorated(): AbstractProductPriceCalculator
    {
        return $this->inner;
    }

    public function calculate(iterable $products, SalesChannelContext $context): void
    {
        // before: runs ahead of the original
        $this->inner->calculate($products, $context);
        // after: runs once prices exist
    }
}

The signature above matches recent versions as far as we know, but check the abstract class in your Shopware version before copying it, because core method signatures can change in major releases.

Registration tells the container which service you wrap, and hands you the original as .inner:

XML
<service id="Acme\Badges\Service\LoggingPriceCalculator"
         decorates="Shopware\Core\Content\Product\SalesChannel\Price\ProductPriceCalculator">
    <argument type="service" id=".inner"/>
</service>

Anyone who asked for the original id now receives your decorator, which calls the original in turn. If two plugins decorate the same service they form a chain; the decoration_priority attribute controls the order. Decorating works through the abstract class and its getDecorated() so that other decorators further up the chain can be reached too.

flowchart LR
    C["Caller asks for<br/>PriceCalculator"] --> D2["Plugin B decorator"]
    D2 --> D1["Plugin A decorator"]
    D1 --> O["Core implementation"]

Each decorator wraps the next; the caller only knows the outermost one.

Services, bundles and loading

A plugin is a Symfony bundle, and bundles can contribute container configuration. When the kernel boots, it builds one container from the core bundles and every active plugin. Their services.xml files are merged, tags are collected and the result is compiled and cached under var/cache/. So:

  • Inactive or uninstalled plugins add nothing to the container.
  • A syntax error in services.xml can break the whole shop on the next cache build. Test in development, and keep the XML schema header so your editor validates it.
  • Anything you change in service configuration needs bin/console cache:clear before it applies.

To see what the container holds, use bin/console debug:container Acme to list services whose id contains the text, and add a service id to see its arguments and tags.

A mini container with decoration

This stand-in container is a plain PHP class with factories as closures. It resolves services lazily, shares one instance per id and supports decorates, including a chain of two decorators with priorities. It is not Symfony's container: it only shows the idea.

PHP A mini container with a decorator chain

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 logging decorator has the higher priority, so it sits outermost: it sees the result after the discount. The container returns the same object on the second call, like Symfony's shared services.

The second stand-in is a tag collector. It models a compiler pass: services declare tags, and a "dispatcher" gathers everything with the subscriber tag.

PHP Collecting tagged services

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: tags, compiler passes, decorates, .inner, getDecorated(). Stand-in: both containers and the collector.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the purpose of the kernel.event_subscriber tag?

    A tag only labels a service. A compiler pass collects services with this tag and registers their subscribed events with the dispatcher.
  2. 2. Why is decoration preferred over copying a core service into your plugin?

    A decorator wraps the original and calls it, so core updates still apply and several plugins can wrap the same service in a chain.
  3. 3. In a decorator's service definition, which argument id gives you the service being decorated?

    Symfony passes the decorated service as .inner, which you inject into the decorator's constructor.
  4. 4. You changed services.xml but your new service is not found. What do you do first?

    The container is compiled and cached, so definition changes only take effect after the cache is rebuilt.
  5. 5. Why should a service avoid storing request-specific state in its properties?

    Services are shared, and queue workers or long-running commands reuse them across many jobs, so per-request data can bleed from one job into the next.

Summary

  • Services are created and wired by Symfony's container; plugins define them in Resources/config/services.xml.
  • Explicit <argument> lines are the predictable style in Shopware, though autowiring is possible.
  • Tags are labels that framework code collects: subscribers, commands, entity definitions, scheduled tasks and message handlers.
  • Decorate core services through their abstract class and getDecorated(); the original arrives as .inner.
  • Active plugins contribute to one compiled container, so clear the cache after changes.
  • The mini container and tag collector are stand-ins for the real container.

Next: Plugin Structure and Lifecycle