Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 30 ยท Practice and Review

Practice Exercises with Solutions

Twelve graded Shopware plugin exercises with hints and solutions: container, decoration, tags, criteria, migrations, N+1, events, routes, config, Twig blocks and HMAC.

Reading about decoration, criteria or event priorities is not the same as writing the code that makes them work. This page gives you twelve exercises that follow the course: services and the container, the Data Abstraction Layer, events and subscribers, routes, configuration, Twig blocks and webhook signatures. Each one has a hint, runnable starter code, tests with the expected output, and a solution you can open after a real attempt.

Shopware cannot run on this site, so every exercise is a plain-PHP stand-in: a few lines that behave like the Shopware or Symfony feature you would use in a real plugin. You are building the idea behind the framework class, not its actual source code. Where the real thing differs, the solution says so. For the real classes, the lessons linked in each section are the reference.

How to use the page:

  • Each editor has starter code that runs as given. Replace the code between the // --- your code --- and // --- tests --- comment lines. The comments in the tests show the output you should get.
  • Hint first, solution last. The hint points at the approach without giving the code away.
  • Compare, don't copy. A different solution that passes the tests is a good solution.
  • The PHP here reports every error level, so a warning such as "Undefined array key" is a bug to fix.
flowchart LR
    A["Services<br/>1 to 3"] --> B["DAL<br/>4 to 6"]
    B --> C["Events<br/>7 and 8"]
    C --> D["Routes and config<br/>9 and 10"]
    D --> E["Twig and security<br/>11 and 12"]

The exercises follow the order of the course, roughly from beginner to advanced.

Services and the container

These exercises cover Services and the Dependency Injection Container.

1. A shared-service container (Beginner)

Implement set() and get(). set() registers a factory (a callable that receives the container). get() calls the factory the first time and returns the same object on every later call. Asking for an unknown id must throw an OutOfBoundsException with the message Service "missing" not found.

Hint: keep two arrays, one for factories and one for built instances.

PHP Exercise 1: a container

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.

Show solution
PHP
final class Container
{
    private array $factories = [];
    private array $instances = [];

    public function set(string $id, callable $factory): void
    {
        $this->factories[$id] = $factory;
        unset($this->instances[$id]);
    }

    public function get(string $id): object
    {
        if (isset($this->instances[$id])) {
            return $this->instances[$id];
        }
        if (!isset($this->factories[$id])) {
            throw new OutOfBoundsException(sprintf('Service "%s" not found', $id));
        }
        return $this->instances[$id] = ($this->factories[$id])($this);
    }
}

Shared instances are the default in the Symfony container that Shopware uses. The real container also compiles all of this ahead of time, resolves constructor arguments by type and detects circular references; see Services and the Container.

2. Decorating a service (Intermediate)

Add decorate(string $id, callable $decorator). The decorator receives the inner service and the container and returns the replacement. After decoration, get($id) returns the decorated service. Decorating twice must stack: the second decorator wraps the first.

Hint: do not build the service yet. Replace the stored factory with a new factory that calls the old one and passes its result to the decorator.

PHP Exercise 2: decoration

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.

Show solution
PHP
final class Container
{
    private array $factories = [];
    private array $instances = [];

    public function set(string $id, callable $factory): void
    {
        $this->factories[$id] = $factory;
    }

    public function decorate(string $id, callable $decorator): void
    {
        $inner = $this->factories[$id] ?? throw new OutOfBoundsException("Cannot decorate unknown service \"$id\"");
        $this->factories[$id] = fn (Container $c) => $decorator($inner($c), $c);
    }

    public function get(string $id): object
    {
        return $this->instances[$id] ??= ($this->factories[$id])($this);
    }
}

The new factory closes over the old one, so decorators stack from the inside out. In Shopware you do this with decorates="..." in services.xml, and the original service is injected as .inner. This is how plugins change core behavior without editing it. Always depend on the interface or abstract class, so that your decorator can sit in front of other decorators.

3. Tagged services with priorities (Intermediate)

Implement a TagRegistry. tag($tag, $serviceId, $priority = 0) registers a service under a tag. tagged($tag) returns the service ids, highest priority first; services with equal priority keep their registration order. An unknown tag gives an empty array.

Hint: usort() is stable in PHP 8, so a comparison on the priority alone keeps ties in registration order.

PHP Exercise 3: tags

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.

Show solution
PHP
final class TagRegistry
{
    private array $tags = [];

    public function tag(string $tag, string $serviceId, int $priority = 0): void
    {
        $this->tags[$tag][] = ['id' => $serviceId, 'priority' => $priority];
    }

    /** @return string[] */
    public function tagged(string $tag): array
    {
        $entries = $this->tags[$tag] ?? [];
        usort($entries, static fn (array $x, array $y) => $y['priority'] <=> $x['priority']);
        return array_column($entries, 'id');
    }
}

This is the idea behind a tagged iterator: a service that receives "all services with tag X" in priority order. Shopware uses tags everywhere (kernel.event_subscriber, shopware.entity.definition, flow.action, shopware.scheduled.task). See Service Tags.

The Data Abstraction Layer

These cover Reading and Writing with Repositories, Database Migrations and Security and Performance.

4. From criteria to SQL (Intermediate)

A Criteria object collects filters, sortings and paging. Write toSql(), which turns it into a SQL string with ? placeholders plus a parameter list. Supported filters: equals, contains (a LIKE with % on both sides) and equalsAny (an IN list; an empty list matches nothing). Every field name must be in the $allowed list, otherwise throw InvalidArgumentException. Values are never put into the SQL string.

Hint: field names cannot be bound as parameters, so a whitelist is the only safe way to use them.

PHP Exercise 4: criteria to SQL

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.

Show solution
PHP
/** @return array{string, array} */
function toSql(string $table, Criteria $criteria, array $allowed): array
{
    $check = static function (string $field) use ($allowed): string {
        if (!in_array($field, $allowed, true)) {
            throw new InvalidArgumentException("Unknown field \"$field\"");
        }
        return $field;
    };

    $where = [];
    $params = [];
    foreach ($criteria->filters as [$type, $field, $value]) {
        $field = $check($field);
        if ($type === 'equals') {
            $where[] = "$field = ?";
            $params[] = $value;
        } elseif ($type === 'contains') {
            $where[] = "$field LIKE ?";
            $params[] = '%' . $value . '%';
        } elseif ($value === []) {
            $where[] = '0 = 1';
        } else {
            $where[] = "$field IN (" . implode(', ', array_fill(0, count($value), '?')) . ')';
            array_push($params, ...$value);
        }
    }

    $sql = 'SELECT * FROM ' . $table;
    if ($where) {
        $sql .= ' WHERE ' . implode(' AND ', $where);
    }
    if ($criteria->sortings) {
        $parts = array_map(
            static fn (array $s) => $check($s[0]) . ' ' . ($s[1] === 'DESC' ? 'DESC' : 'ASC'),
            $criteria->sortings
        );
        $sql .= ' ORDER BY ' . implode(', ', $parts);
    }
    if ($criteria->limit !== null) {
        $sql .= ' LIMIT ' . $criteria->limit . ' OFFSET ' . $criteria->offset;
    }
    return [$sql, $params];
}

The real DAL does far more (nested filters, associations, translations, inheritance, versions), and it takes field names from the entity definition, which plays the role of the whitelist. A real contains filter also escapes % and _ inside the value; this one does not.

5. A migration runner (Intermediate)

Implement migrate(). Migrations come as timestamp => callable(PDO) in any order. Run the ones that have not run yet in ascending timestamp order, record each in a migration table, and return the list of timestamps that ran. A second call must run nothing.

Hint: create the bookkeeping table with IF NOT EXISTS, then compare. Wrap each step and its bookkeeping row in one transaction.

PHP Exercise 5: migrate

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.

Show solution
PHP
/** @return int[] timestamps that were executed */
function migrate(PDO $pdo, array $migrations): array
{
    $pdo->exec('CREATE TABLE IF NOT EXISTS migration (creation_timestamp INTEGER PRIMARY KEY)');
    $done = array_map('intval', $pdo->query('SELECT creation_timestamp FROM migration')->fetchAll(PDO::FETCH_COLUMN));

    ksort($migrations);
    $ran = [];
    foreach ($migrations as $timestamp => $step) {
        if (in_array($timestamp, $done, true)) {
            continue;
        }
        $pdo->beginTransaction();
        try {
            $step($pdo);
            $pdo->prepare('INSERT INTO migration (creation_timestamp) VALUES (?)')->execute([$timestamp]);
            $pdo->commit();
        } catch (Throwable $e) {
            $pdo->rollBack();
            throw $e;
        }
        $ran[] = $timestamp;
    }
    return $ran;
}

Shopware's migration table works the same way: each class has a creation timestamp, and the runner executes the ones not yet recorded, oldest first. MySQL commits DDL statements implicitly, so on MySQL a failed step can leave a half-applied change; write steps so that a second try works (CREATE TABLE IF NOT EXISTS). See Database Migrations.

6. Remove an N+1 query (Advanced)

customerNamesByOrder() returns a map from order id to customer name. The starter runs one query per order, the classic N+1 problem. Rewrite it so that it runs one query for all orders (and none when the list is empty). $queries counts the queries you run.

Hint: collect the distinct customer ids first, fetch them with an IN list, then look the names up in an array.

PHP Exercise 6: N+1

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.

Show solution
PHP
/** @return array<int, string> */
function customerNamesByOrder(PDO $pdo, array $orders, int &$queries): array
{
    if ($orders === []) {
        return [];
    }
    $ids = array_values(array_unique(array_column($orders, 'customer_id')));

    $stmt = $pdo->prepare('SELECT id, name FROM customer WHERE id IN (' . implode(', ', array_fill(0, count($ids), '?')) . ')');
    $stmt->execute($ids);
    $queries++;
    $byId = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

    $names = [];
    foreach ($orders as $order) {
        $names[$order['id']] = $byId[$order['customer_id']] ?? '';
    }
    return $names;
}

In Shopware the equivalent fix is $criteria->addAssociation('orderCustomer'): the DAL loads the association for the whole result in one extra query instead of one per entity. The opposite mistake is adding associations you never read. Both are discussed in Security and Performance.

Events and subscribers

These cover Subscribers and Core Events.

7. A dispatcher with priorities (Beginner)

Implement dispatch(). Listeners with a higher priority run first; equal priorities keep their registration order. After each listener, check $event->propagationStopped; if it is true, stop calling further listeners. dispatch() returns the event.

Hint: listen() already groups listeners by priority. Sort the priorities in descending order with krsort().

PHP Exercise 7: dispatcher

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.

Show solution
PHP
final class Dispatcher
{
    private array $listeners = [];

    public function listen(string $name, callable $listener, int $priority = 0): void
    {
        $this->listeners[$name][$priority][] = $listener;
    }

    public function dispatch(string $name, Event $event): Event
    {
        $byPriority = $this->listeners[$name] ?? [];
        krsort($byPriority);
        foreach ($byPriority as $listeners) {
            foreach ($listeners as $listener) {
                if ($event->propagationStopped) {
                    return $event;
                }
                $listener($event);
            }
        }
        return $event;
    }
}

This is the heart of Symfony's EventDispatcher, which Shopware uses for everything from product.loaded to page events. Check the stop flag before each listener so a listener that stops propagation is still the last one that ran. Priorities let you run before or after core subscribers, but depending on the order of other plugins is fragile.

8. Register a subscriber (Intermediate)

Write addSubscriber(). It reads getSubscribedEvents() from the object and registers the listeners. The map's value can be a method name, [method, priority], or a list of [method, priority] pairs.

Hint: if the value is a string, you have one method. If its first element is a string, you have [method, priority]. Otherwise it is a list.

PHP Exercise 8: subscribers

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.

Show solution
PHP
function addSubscriber(Dispatcher $dispatcher, object $subscriber): void
{
    foreach ($subscriber::getSubscribedEvents() as $event => $params) {
        if (is_string($params)) {
            $dispatcher->listen($event, [$subscriber, $params]);
        } elseif (is_string($params[0])) {
            $dispatcher->listen($event, [$subscriber, $params[0]], $params[1] ?? 0);
        } else {
            foreach ($params as $listener) {
                $dispatcher->listen($event, [$subscriber, $listener[0]], $listener[1] ?? 0);
            }
        }
    }
}

These are exactly the three shapes Symfony allows in getSubscribedEvents(). Shopware subscribers register through the kernel.event_subscriber tag, and the container then calls code like this for you. The method is looked up lazily in the real framework, so keep subscriber constructors cheap: a subscriber is built even when its event never fires.

Routes and configuration

These cover Custom Store API Routes and Plugin Configuration.

9. A route matcher (Intermediate)

Implement Router::dispatch(). Patterns can contain placeholders that match one path segment. A match calls the handler with an array of the captured parameters. If no pattern matches the path, answer 404. If the path matches but not for that HTTP method, answer 405 and list the allowed methods.

Hint: turn each pattern into a regular expression with named groups. Use preg_quote() on the fixed parts, and keep only string keys from the match array.

PHP Exercise 9: router

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.

Show solution
PHP
final class Router
{
    private array $routes = [];

    public function add(string $method, string $pattern, callable $handler): void
    {
        $this->routes[] = [$method, $pattern, $handler];
    }

    /** @return array{int, string} */
    public function dispatch(string $method, string $path): array
    {
        $allowed = [];
        foreach ($this->routes as [$routeMethod, $pattern, $handler]) {
            if (!preg_match($this->toRegex($pattern), $path, $matches)) {
                continue;
            }
            if ($routeMethod === $method) {
                $params = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);
                return [200, $handler($params)];
            }
            $allowed[] = $routeMethod;
        }
        return $allowed ? [405, 'Allowed: ' . implode(', ', $allowed)] : [404, 'Not Found'];
    }

    private function toRegex(string $pattern): string
    {
        $regex = '';
        foreach (preg_split('/(\{\w+\})/', $pattern, -1, PREG_SPLIT_DELIM_CAPTURE) as $part) {
            $regex .= preg_match('/^\{(\w+)\}$/', $part, $m)
                ? '(?P<' . $m[1] . '>[^/]+)'
                : preg_quote($part, '#');
        }
        return '#^' . $regex . '$#';
    }
}

A real Store API route is matched by Symfony's router in the same spirit, using the path and methods from the #[Route] attribute. Telling "wrong method" from "wrong path" matters for API clients: 405 and 404 mean different things. See Routing with Attributes.

10. Config with sales channel fallback (Beginner)

Implement get(string $key, ?string $channelId = null, mixed $default = null). Return the value stored for the sales channel when there is one, otherwise the global value, otherwise $default. Only the absence of a value counts as "not set": false, 0 and '' are real values and must not fall back.

Hint: isset() and ?? treat null as missing, which is what you want, but empty() would break the test with false.

PHP Exercise 10: config fallback

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.

Show solution
PHP
final class ConfigStore
{
    /** @var array<string, array<string, mixed>> key => channelId (or '') => value */
    private array $values = [];

    public function set(string $key, mixed $value, ?string $channelId = null): void
    {
        $this->values[$key][$channelId ?? ''] = $value;
    }

    public function get(string $key, ?string $channelId = null, mixed $default = null): mixed
    {
        $perChannel = $this->values[$key] ?? [];
        if ($channelId !== null && array_key_exists($channelId, $perChannel)) {
            return $perChannel[$channelId];
        }
        return array_key_exists('', $perChannel) ? $perChannel[''] : $default;
    }
}

SystemConfigService follows the same idea: get('AcmePlugin.config.key', $salesChannelId) returns the channel value and falls back to the global one. Pass the sales channel id whenever you know it, because a value that differs per channel is a common requirement. The caveat to remember is that what the admin treats as "unset" can differ from PHP's null, so test the case your plugin depends on.

Twig and security

These cover Storefront Templates with Twig and Apps, Webhooks and Signatures.

11. Template blocks with parent() (Advanced)

Write render($base, $overrides, $vars). The base template contains blocks like {% block title %}default{% endblock %}. For each block, if $overrides has content for it, use that instead; inside an override, {{ parent() }} is replaced by the base block's default content. Then replace {{ name }} with the HTML-escaped variable.

Hint: use preg_replace_callback() over the base. Resolve parent() before you substitute variables, and escape variables last.

PHP Exercise 11: blocks and parent

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.

Show solution
PHP
function render(string $base, array $overrides, array $vars): string
{
    $out = preg_replace_callback(
        '/\{% block (\w+) %\}(.*?)\{% endblock %\}/s',
        static function (array $m) use ($overrides): string {
            if (!isset($overrides[$m[1]])) {
                return $m[2];
            }
            return str_replace('{{ parent() }}', $m[2], $overrides[$m[1]]);
        },
        $base
    );

    return preg_replace_callback(
        '/\{\{ (\w+) \}\}/',
        static fn (array $m) => htmlspecialchars((string) ($vars[$m[1]] ?? ''), ENT_QUOTES),
        $out
    );
}

Shopware's storefront uses Twig's real inheritance with sw_extends and {% block %}; this stand-in captures only the override and parent() idea (it ignores nested blocks, filters and loops). In a plugin you add a template under Resources/views/storefront/... that extends the core file, override one block and call {{ parent() }} to keep what was there. Twig escapes {{ }} output by default, which is why the stand-in does too.

12. Verify a webhook signature (Intermediate)

An app server receives a webhook with a signature header: the HMAC-SHA256 of the raw body, hex encoded, computed with a shared secret. Implement verify(). Compare in constant time, and return false for a missing or empty header.

Hint: hash_hmac('sha256', $body, $secret) computes the expected value; hash_equals() compares without leaking where the strings differ.

PHP Exercise 12: HMAC verify

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.

Show solution
PHP
function verify(string $secret, string $body, ?string $signature): bool
{
    if ($signature === null || $signature === '') {
        return false;
    }
    return hash_equals(hash_hmac('sha256', $body, $secret), $signature);
}

Always verify the raw body, before decoding JSON: re-encoding changes bytes and breaks the signature. Using == instead of hash_equals() can leak timing information. The registration handshake and the exact header names of the app system are in Apps, Webhooks and Signatures, and the general technique, including replay protection, is in Webhooks and Signatures.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the criteria builder in exercise 4 check field names against a list instead of binding them as parameters?

    Placeholders stand for values only. Anything that becomes part of the SQL structure must come from a trusted list.
  2. 2. What problem does loading associations for the whole result set solve?

    Loading related rows for all entities at once replaces many small queries with one extra query.
  3. 3. Which approach lets you wrap a core service without editing it?

    A decorator implements the same interface, receives the inner service and adds behavior around it.
  4. 4. Why compare signatures with hash_equals()?

    A plain comparison can stop at the first different character, which leaks timing information to an attacker.

Summary

  • A container, decoration and tags are small ideas: factories, wrapped factories and ordered lists of ids.
  • Criteria become parameterized SQL, with identifiers from a whitelist; migrations are recorded by timestamp and run once.
  • Load related data in bulk to avoid N+1 queries.
  • A dispatcher sorts by priority and honors a stop flag; subscribers declare their events in a static map.
  • Route matching distinguishes 404 from 405; configuration falls back from channel to global without confusing false with "unset".
  • Verify raw bodies with HMAC and constant-time comparison.

Keep going with Interview Questions.