Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 62 ยท Services and the Container

Tags, Decorators and Service Locators

Use service tags and AutowireIterator to collect services, decorate a service with AsDecorator, make services lazy, and use service locators, with runnable chain examples.

Autowiring answers "give me the service of this type". Sometimes you need a different question answered: "give me all services that can do this", or "wrap this service with extra behavior without changing its code". Symfony's answers are tags, decoration, lazy services and service locators. They are what makes large applications extensible: the framework itself uses them for event listeners, console commands, form types, Twig extensions and much more.

This lesson shows each tool with real Symfony code (read-only) and two runnable stand-ins: a collector that behaves like a tagged iterator with priorities, and a decorator chain.

Tags

A tag is a label on a service definition. Tags themselves do nothing; some other code looks for them. With the App\: prototype and autoconfigure, you rarely write tags by hand, but the idea helps you read the rest of the configuration.

Imagine a report exporter that supports several formats. Each format is its own class implementing one interface. To let the exporter find them all, tag every implementation. You can tag in YAML:

YAML
services:
    App\Export\CsvFormatter:
        tags: [{ name: 'app.formatter', priority: 10 }]
    App\Export\JsonFormatter:
        tags: ['app.formatter']

or, much shorter, tag the interface once with an attribute. Every class that implements it is tagged automatically through autoconfigure:

PHP
<?php
namespace App\Export;

use Symfony\Component\DependencyInjection\Attribute\AutoconfigureTag;

#[AutoconfigureTag('app.formatter')]
interface FormatterInterface
{
    public function supports(string $format): bool;

    public function format(array $rows): string;
}

Collecting tagged services

The consumer asks for the whole group with #[AutowireIterator]. The container injects an iterable of services, each created only when you reach it in the loop:

PHP
<?php
namespace App\Export;

use Symfony\Component\DependencyInjection\Attribute\AutowireIterator;

final class ReportExporter
{
    /** @param iterable<FormatterInterface> $formatters */
    public function __construct(
        #[AutowireIterator('app.formatter')]
        private iterable $formatters,
    ) {
    }

    public function export(array $rows, string $format): string
    {
        foreach ($this->formatters as $formatter) {
            if ($formatter->supports($format)) {
                return $formatter->format($rows);
            }
        }

        throw new \InvalidArgumentException("No formatter supports \"{$format}\".");
    }
}

Adding a new format now means adding one class; ReportExporter and services.yaml stay untouched. This is the open/closed principle, delivered by the container. Older code uses #[TaggedIterator('app.formatter')], which is deprecated in favor of AutowireIterator. The YAML equivalent is !tagged_iterator app.formatter.

Order comes from the tag's priority (higher first; the default is 0). You can also key the iterable: #[AutowireIterator('app.formatter', indexAttribute: 'format')] uses a format attribute on the tag as the array key, so $formatters['csv'] becomes possible.

flowchart LR
    I["interface tagged<br/>app.formatter"] --> A["CsvFormatter"]
    I --> B["JsonFormatter"]
    I --> C["XmlFormatter"]
    A --> X["ReportExporter<br/>receives iterable"]
    B --> X
    C --> X

One tag, many services: the consumer receives the whole group without naming any member.

PHP A tagged-iterator collector (stand-in)

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 output shows the priority order (CSV, then JSON, then the fallback) and that a format nobody handles ends up at the low-priority fallback. Services are only created when the loop reaches them, which is why json never touches the fallback.

Decoration

A decorator wraps an existing service with the same interface, adds behavior and delegates the rest. Think logging, caching or metrics around a service you do not want to edit, perhaps because it comes from a vendor package. Symfony lets you replace a service with its decorator everywhere, without changing a single consumer:

PHP
<?php
namespace App\Mail;

use Symfony\Component\DependencyInjection\Attribute\AsDecorator;
use Symfony\Component\DependencyInjection\Attribute\AutowireDecorated;

#[AsDecorator(decorates: MailSenderInterface::class)]
final class LoggingMailSender implements MailSenderInterface
{
    public function __construct(
        #[AutowireDecorated] private MailSenderInterface $inner,
        private LoggerInterface $logger,
    ) {
    }

    public function send(string $to, string $subject): void
    {
        $this->logger->info('Sending mail', ['to' => $to]);
        $this->inner->send($to, $subject);
    }
}

#[AutowireDecorated] injects the original service (the inner). Every class that asks for MailSenderInterface now receives LoggingMailSender. You can stack several decorators; give each a priority to control the order in which they wrap the inner service. YAML offers the same via decorates: and decoration_priority:.

PHP A decorator chain (stand-in)

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 consumer calls one method, yet three classes cooperate: logging, then the prefix, then SMTP. The log lines appear around the inner call, which is exactly what an outer decorator can do.

Lazy services

Creating a service can be expensive: it may open a connection or read a large file. A lazy service is injected as a lightweight proxy, and the real object is built only on the first method call. Mark one in code:

PHP
<?php
use Symfony\Component\DependencyInjection\Attribute\Autowire;

final class ReportController
{
    public function __construct(
        #[Autowire(service: 'app.expensive_client', lazy: true)]
        private ExpensiveClient $client,
    ) {
    }
}

or in YAML with lazy: true on the service definition. Symfony generates the proxy for you, using PHP's native lazy objects where the framework and PHP version support them and generated proxy classes otherwise. A generated proxy is a subclass, so a final class may not be lazy-able on older setups. Proxies also add a little indirection, so use them for expensive, rarely used dependencies rather than everywhere.

Service locators

An iterator gives you every tagged service. A service locator gives you a small PSR-11 container with only the services you list, fetched by key when you need one. It is the right tool when you pick a service based on runtime data, such as a payment gateway chosen by the order's method:

PHP
<?php
namespace App\Payment;

use Psr\Container\ContainerInterface;
use Symfony\Component\DependencyInjection\Attribute\AutowireLocator;

final class PaymentProcessor
{
    public function __construct(
        #[AutowireLocator('app.gateway', indexAttribute: 'method')]
        private ContainerInterface $gateways,
    ) {
    }

    public function pay(string $method, int $cents): void
    {
        if (!$this->gateways->has($method)) {
            throw new \DomainException("Unknown payment method \"{$method}\".");
        }

        $this->gateways->get($method)->charge($cents);
    }
}

Compared with injecting the whole container, a locator is restricted: it can only return the services you declared, which keeps dependencies explicit and testable. Compared with an iterator, it looks up one service directly instead of looping, and creates only that service.

Never inject the full container (ContainerInterface without a locator attribute) into your own services. It hides what a class really needs, defeats compile-time checks and makes tests awkward. If you catch yourself doing this, a tagged iterator or a service locator is almost always the better answer.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a service tag?

    Tags mark services so another part of the system (the event dispatcher, console, your own collector) can find them. A tag does nothing by itself.
  2. 2. Which attribute injects all services that carry the tag app.formatter?

    AutowireIterator injects an iterable of the tagged services, created lazily as you loop over them.
  3. 3. What does #[AsDecorator(decorates: MailSenderInterface::class)] do?

    The decorator takes the original service's place for all consumers, and #[AutowireDecorated] gives it the inner service to delegate to.
  4. 4. When is a service locator a better fit than a tagged iterator?

    A locator fetches one service by key on demand, creating only that one. An iterator is for processing the whole group.

Summary

  • Tags label services; #[AutoconfigureTag] on an interface tags all implementations, and #[AutowireIterator] collects them lazily, ordered by priority.
  • Decoration wraps a service with another implementing the same interface: #[AsDecorator] plus #[AutowireDecorated] for the inner service.
  • Lazy services are proxies that build the real object on first use; use them for expensive, rarely needed dependencies.
  • A service locator (#[AutowireLocator]) offers a restricted container for picking one service by key at runtime.
  • Do not inject the whole container into application services.

Next, look at what happens when Symfony compiles all of this, and how to extend it, in Compiler Passes and Bundle Extensions.