How to Work with Service Tags

How to Work with Service Tags

Service tags are a way to tell Symfony or other third-party bundles that your service should be registered in some special way. Take the following example:

  • YAML

    1. # config/services.yaml
    2. services:
    3. App\Twig\AppExtension:
    4. tags: ['twig.extension']
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services
    6. https://symfony.com/schema/dic/services/services-1.0.xsd">
    7. <services>
    8. <service id="App\Twig\AppExtension">
    9. <tag name="twig.extension"/>
    10. </service>
    11. </services>
    12. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use App\Twig\AppExtension;
    4. return function(ContainerConfigurator $configurator) {
    5. $services = $configurator->services();
    6. $services->set(AppExtension::class)
    7. ->tag('twig.extension');
    8. };

Services tagged with the twig.extension tag are collected during the initialization of TwigBundle and added to Twig as extensions.

Other tags are used to integrate your services into other systems. For a list of all the tags available in the core Symfony Framework, check out Built-in Symfony Service Tags. Each of these has a different effect on your service and many tags require additional arguments (beyond the name parameter).

For most users, this is all you need to know. If you want to go further and learn how to create your own custom tags, keep reading.

Autoconfiguring Tags

If you enable autoconfigure, then some tags are automatically applied for you. That’s true for the twig.extension tag: the container sees that your class extends AbstractExtension (or more accurately, that it implements ExtensionInterface) and adds the tag for you.

If you want to apply tags automatically for your own services, use the _instanceof option:

  • YAML

    1. # config/services.yaml
    2. services:
    3. # this config only applies to the services created by this file
    4. _instanceof:
    5. # services whose classes are instances of CustomInterface will be tagged automatically
    6. App\Security\CustomInterface:
    7. tags: ['app.custom_tag']
    8. # ...
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <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 https://symfony.com/schema/dic/services/services-1.0.xsd">
    4. <services>
    5. <!-- this config only applies to the services created by this file -->
    6. <instanceof id="App\Security\CustomInterface" autowire="true">
    7. <!-- services whose classes are instances of CustomInterface will be tagged automatically -->
    8. <tag name="app.custom_tag"/>
    9. </instanceof>
    10. </services>
    11. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use App\Security\CustomInterface;
    4. return function(ContainerConfigurator $configurator) {
    5. $services = $configurator->services();
    6. // this config only applies to the services created by this file
    7. $services
    8. ->instanceof(CustomInterface::class)
    9. // services whose classes are instances of CustomInterface will be tagged automatically
    10. ->tag('app.custom_tag');
    11. };

For more advanced needs, you can define the automatic tags using the [registerForAutoconfiguration()](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/DependencyInjection/ContainerBuilder.php "Symfony\Component\DependencyInjection\ContainerBuilder::registerForAutoconfiguration()") method.

In a Symfony application, call this method in your kernel class:

  1. // src/Kernel.php
  2. class Kernel extends BaseKernel
  3. {
  4. // ...
  5. protected function build(ContainerBuilder $container): void
  6. {
  7. $container->registerForAutoconfiguration(CustomInterface::class)
  8. ->addTag('app.custom_tag')
  9. ;
  10. }
  11. }

In a Symfony bundle, call this method in the load() method of the bundle extension class:

  1. // src/DependencyInjection/MyBundleExtension.php
  2. class MyBundleExtension extends Extension
  3. {
  4. // ...
  5. public function load(array $configs, ContainerBuilder $container): void
  6. {
  7. $container->registerForAutoconfiguration(CustomInterface::class)
  8. ->addTag('app.custom_tag')
  9. ;
  10. }
  11. }

Creating custom Tags

Tags on their own don’t actually alter the functionality of your services in any way. But if you choose to, you can ask a container builder for a list of all services that were tagged with some specific tag. This is useful in compiler passes where you can find these services and use or modify them in some specific way.

For example, if you are using Swift Mailer you might imagine that you want to implement a “transport chain”, which is a collection of classes implementing \Swift_Transport. Using the chain, you’ll want Swift Mailer to try several ways of transporting the message until one succeeds.

To begin with, define the TransportChain class:

  1. // src/Mail/TransportChain.php
  2. namespace App\Mail;
  3. class TransportChain
  4. {
  5. private $transports;
  6. public function __construct()
  7. {
  8. $this->transports = [];
  9. }
  10. public function addTransport(\Swift_Transport $transport): void
  11. {
  12. $this->transports[] = $transport;
  13. }
  14. }

Then, define the chain as a service:

  • YAML

    1. # config/services.yaml
    2. services:
    3. App\Mail\TransportChain: ~
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services
    6. https://symfony.com/schema/dic/services/services-1.0.xsd">
    7. <services>
    8. <service id="App\Mail\TransportChain"/>
    9. </services>
    10. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use App\Mail\TransportChain;
    4. return function(ContainerConfigurator $configurator) {
    5. $services = $configurator->services();
    6. $services->set(TransportChain::class);
    7. };

Define Services with a Custom Tag

Now you might want several of the \Swift_Transport classes to be instantiated and added to the chain automatically using the addTransport() method. For example, you may add the following transports as services:

  • YAML

    1. # config/services.yaml
    2. services:
    3. Swift_SmtpTransport:
    4. arguments: ['%mailer_host%']
    5. tags: ['app.mail_transport']
    6. Swift_SendmailTransport:
    7. tags: ['app.mail_transport']
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services
    6. https://symfony.com/schema/dic/services/services-1.0.xsd">
    7. <services>
    8. <service id="Swift_SmtpTransport">
    9. <argument>%mailer_host%</argument>
    10. <tag name="app.mail_transport"/>
    11. </service>
    12. <service id="Swift_SendmailTransport">
    13. <tag name="app.mail_transport"/>
    14. </service>
    15. </services>
    16. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. return function(ContainerConfigurator $configurator) {
    4. $services = $configurator->services();
    5. $services->set(\Swift_SmtpTransport::class)
    6. ->args(['%mailer_host%'])
    7. ->tag('app.mail_transport')
    8. ;
    9. $services->set(\Swift_SendmailTransport::class)
    10. ->tag('app.mail_transport')
    11. ;
    12. };

Notice that each service was given a tag named app.mail_transport. This is the custom tag that you’ll use in your compiler pass. The compiler pass is what makes this tag “mean” something.

Create a Compiler Pass

You can now use a compiler pass to ask the container for any services with the app.mail_transport tag:

  1. // src/DependencyInjection/Compiler/MailTransportPass.php
  2. namespace App\DependencyInjection\Compiler;
  3. use App\Mail\TransportChain;
  4. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  5. use Symfony\Component\DependencyInjection\ContainerBuilder;
  6. use Symfony\Component\DependencyInjection\Reference;
  7. class MailTransportPass implements CompilerPassInterface
  8. {
  9. public function process(ContainerBuilder $container): void
  10. {
  11. // always first check if the primary service is defined
  12. if (!$container->has(TransportChain::class)) {
  13. return;
  14. }
  15. $definition = $container->findDefinition(TransportChain::class);
  16. // find all service IDs with the app.mail_transport tag
  17. $taggedServices = $container->findTaggedServiceIds('app.mail_transport');
  18. foreach ($taggedServices as $id => $tags) {
  19. // add the transport service to the TransportChain service
  20. $definition->addMethodCall('addTransport', [new Reference($id)]);
  21. }
  22. }
  23. }

Register the Pass with the Container

In order to run the compiler pass when the container is compiled, you have to add the compiler pass to the container in a bundle extension or from your kernel:

  1. // src/Kernel.php
  2. namespace App;
  3. use App\DependencyInjection\Compiler\MailTransportPass;
  4. use Symfony\Component\HttpKernel\Kernel as BaseKernel;
  5. // ...
  6. class Kernel extends BaseKernel
  7. {
  8. // ...
  9. protected function build(ContainerBuilder $container): void
  10. {
  11. $container->addCompilerPass(new MailTransportPass());
  12. }
  13. }

Tip

When implementing the CompilerPassInterface in a service extension, you do not need to register it. See the components documentation for more information.

Adding Additional Attributes on Tags

Sometimes you need additional information about each service that’s tagged with your tag. For example, you might want to add an alias to each member of the transport chain.

To begin with, change the TransportChain class:

  1. class TransportChain
  2. {
  3. private $transports;
  4. public function __construct()
  5. {
  6. $this->transports = [];
  7. }
  8. public function addTransport(\Swift_Transport $transport, $alias): void
  9. {
  10. $this->transports[$alias] = $transport;
  11. }
  12. public function getTransport($alias): ?\Swift_Transport
  13. {
  14. if (array_key_exists($alias, $this->transports)) {
  15. return $this->transports[$alias];
  16. }
  17. return null;
  18. }
  19. }

As you can see, when addTransport() is called, it takes not only a Swift_Transport object, but also a string alias for that transport. So, how can you allow each tagged transport service to also supply an alias?

To answer this, change the service declaration:

  • YAML

    1. # config/services.yaml
    2. services:
    3. Swift_SmtpTransport:
    4. arguments: ['%mailer_host%']
    5. tags:
    6. - { name: 'app.mail_transport', alias: 'smtp' }
    7. Swift_SendmailTransport:
    8. tags:
    9. - { name: 'app.mail_transport', alias: 'sendmail' }
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services
    6. https://symfony.com/schema/dic/services/services-1.0.xsd">
    7. <services>
    8. <service id="Swift_SmtpTransport">
    9. <argument>%mailer_host%</argument>
    10. <tag name="app.mail_transport" alias="smtp"/>
    11. </service>
    12. <service id="Swift_SendmailTransport">
    13. <tag name="app.mail_transport" alias="sendmail"/>
    14. </service>
    15. </services>
    16. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. return function(ContainerConfigurator $configurator) {
    4. $services = $configurator->services();
    5. $services->set(\Swift_SmtpTransport::class)
    6. ->args(['%mailer_host%'])
    7. ->tag('app.mail_transport', ['alias' => 'smtp'])
    8. ;
    9. $services->set(\Swift_SendmailTransport::class)
    10. ->tag('app.mail_transport', ['alias' => 'sendmail'])
    11. ;
    12. };

Tip

In YAML format, you may provide the tag as a simple string as long as you don’t need to specify additional attributes. The following definitions are equivalent.

  1. # config/services.yaml
  2. services:
  3. # Compact syntax
  4. Swift_SendmailTransport:
  5. class: \Swift_SendmailTransport
  6. tags: ['app.mail_transport']
  7. # Verbose syntax
  8. Swift_SendmailTransport:
  9. class: \Swift_SendmailTransport
  10. tags:
  11. - { name: 'app.mail_transport' }

Notice that you’ve added a generic alias key to the tag. To actually use this, update the compiler:

  1. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  2. use Symfony\Component\DependencyInjection\ContainerBuilder;
  3. use Symfony\Component\DependencyInjection\Reference;
  4. class TransportCompilerPass implements CompilerPassInterface
  5. {
  6. public function process(ContainerBuilder $container): void
  7. {
  8. // ...
  9. foreach ($taggedServices as $id => $tags) {
  10. // a service could have the same tag twice
  11. foreach ($tags as $attributes) {
  12. $definition->addMethodCall('addTransport', [
  13. new Reference($id),
  14. $attributes['alias']
  15. ]);
  16. }
  17. }
  18. }
  19. }

The double loop may be confusing. This is because a service can have more than one tag. You tag a service twice or more with the app.mail_transport tag. The second foreach loop iterates over the app.mail_transport tags set for the current service and gives you the attributes.

Reference Tagged Services

Symfony provides a shortcut to inject all services tagged with a specific tag, which is a common need in some applications, so you don’t have to write a compiler pass just for that.

In the following example, all services tagged with app.handler are passed as first constructor argument to the App\HandlerCollection service:

  • YAML

    1. # config/services.yaml
    2. services:
    3. App\Handler\One:
    4. tags: ['app.handler']
    5. App\Handler\Two:
    6. tags: ['app.handler']
    7. App\HandlerCollection:
    8. # inject all services tagged with app.handler as first argument
    9. arguments:
    10. - !tagged_iterator app.handler
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services
    6. https://symfony.com/schema/dic/services/services-1.0.xsd">
    7. <services>
    8. <service id="App\Handler\One">
    9. <tag name="app.handler"/>
    10. </service>
    11. <service id="App\Handler\Two">
    12. <tag name="app.handler"/>
    13. </service>
    14. <service id="App\HandlerCollection">
    15. <!-- inject all services tagged with app.handler as first argument -->
    16. <argument type="tagged_iterator" tag="app.handler"/>
    17. </service>
    18. </services>
    19. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. return function(ContainerConfigurator $configurator) {
    4. $services = $configurator->services();
    5. $services->set(App\Handler\One::class)
    6. ->tag('app.handler')
    7. ;
    8. $services->set(App\Handler\Two::class)
    9. ->tag('app.handler')
    10. ;
    11. $services->set(App\HandlerCollection::class)
    12. // inject all services tagged with app.handler as first argument
    13. ->args([tagged_iterator('app.handler')])
    14. ;
    15. };

After compilation the HandlerCollection service is able to iterate over your application handlers:

  1. // src/HandlerCollection.php
  2. namespace App;
  3. class HandlerCollection
  4. {
  5. public function __construct(iterable $handlers)
  6. {
  7. }
  8. }

See also

See also tagged locator services

Tagged Services with Priority

New in version 4.4: The ability to prioritize tagged services was introduced in Symfony 4.4.

The tagged services can be prioritized using the priority attribute. The priority is a positive or negative integer. The higher the number, the earlier the tagged service will be located in the collection:

  • YAML

    1. # config/services.yaml
    2. services:
    3. App\Handler\One:
    4. tags:
    5. - { name: 'app.handler', priority: 20 }
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services
    6. https://symfony.com/schema/dic/services/services-1.0.xsd">
    7. <services>
    8. <service id="App\Handler\One">
    9. <tag name="app.handler" priority="20"/>
    10. </service>
    11. </services>
    12. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use App\Handler\One;
    4. return function(ContainerConfigurator $configurator) {
    5. $services = $configurator->services();
    6. $services->set(One::class)
    7. ->tag('app.handler', ['priority' => 20])
    8. ;
    9. };

Another option, which is particularly useful when using autoconfiguring tags, is to implement the static getDefaultPriority() method on the service itself:

  1. // src/Handler/One.php
  2. namespace App\Handler;
  3. class One
  4. {
  5. public static function getDefaultPriority(): int
  6. {
  7. return 3;
  8. }
  9. }

If you want to have another method defining the priority (e.g. getPriority() rather than getDefaultPriority()), you can define it in the configuration of the collecting service:

  • YAML

    1. # config/services.yaml
    2. services:
    3. App\HandlerCollection:
    4. # inject all services tagged with app.handler as first argument
    5. arguments:
    6. - !tagged_iterator { tag: app.handler, default_priority_method: getPriority }
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services
    6. https://symfony.com/schema/dic/services/services-1.0.xsd">
    7. <services>
    8. <service id="App\HandlerCollection">
    9. <argument type="tagged_iterator" tag="app.handler" default-priority-method="getPriority"/>
    10. </service>
    11. </services>
    12. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument;
    4. return function (ContainerConfigurator $configurator) {
    5. $services = $configurator->services();
    6. // ...
    7. $services->set(App\HandlerCollection::class)
    8. ->args([
    9. tagged_iterator('app.handler', null, null, 'getPriority'),
    10. ])
    11. ;
    12. };

Tagged Services with Index

If you want to retrieve a specific service within the injected collection you can use the index_by and default_index_method options of the argument in combination with !tagged_iterator.

Using the previous example, this service configuration creates a collection indexed by the key attribute:

  • YAML

    1. # config/services.yaml
    2. services:
    3. App\Handler\One:
    4. tags:
    5. - { name: 'app.handler', key: 'handler_one' }
    6. App\Handler\Two:
    7. tags:
    8. - { name: 'app.handler', key: 'handler_two' }
    9. App\HandlerCollection:
    10. arguments: [!tagged_iterator { tag: 'app.handler', index_by: 'key' }]
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services
    6. https://symfony.com/schema/dic/services/services-1.0.xsd">
    7. <services>
    8. <service id="App\Handler\One">
    9. <tag name="app.handler" key="handler_one"/>
    10. </service>
    11. <service id="App\Handler\Two">
    12. <tag name="app.handler" key="handler_two"/>
    13. </service>
    14. <service id="App\HandlerCollection">
    15. <argument type="tagged_iterator" tag="app.handler" index-by="key"/>
    16. </service>
    17. </services>
    18. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use App\Handler\One;
    4. use App\Handler\Two;
    5. use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument;
    6. return function (ContainerConfigurator $configurator) {
    7. $services = $configurator->services();
    8. $services->set(One::class)
    9. ->tag('app.handler', ['key' => 'handler_one']);
    10. $services->set(Two::class)
    11. ->tag('app.handler', ['key' => 'handler_two']);
    12. $services->set(App\HandlerCollection::class)
    13. ->args([
    14. // 2nd argument is the index attribute name
    15. tagged_iterator('app.handler', 'key'),
    16. ])
    17. ;
    18. };

After compilation the HandlerCollection is able to iterate over your application handlers. To retrieve a specific service from the iterator, call the iterator_to_array() function and then use the key attribute to get the array element. For example, to retrieve the handler_two handler:

  1. // src/Handler/HandlerCollection.php
  2. namespace App\Handler;
  3. class HandlerCollection
  4. {
  5. public function __construct(iterable $handlers)
  6. {
  7. $handlers = $handlers instanceof \Traversable ? iterator_to_array($handlers) : $handlers;
  8. $handlerTwo = $handlers['handler_two'];
  9. }
  10. }

Tip

Just like the priority, you can also implement a static getDefaultIndexName() method in the handlers and omit the index attribute (key):

  1. // src/Handler/One.php
  2. namespace App\Handler;
  3. class One
  4. {
  5. // ...
  6. public static function getDefaultIndexName(): string
  7. {
  8. return 'handler_one';
  9. }
  10. }

You also can define the name of the static method to implement on each service with the default_index_method attribute on the tagged argument:

  • YAML

    1. # config/services.yaml
    2. services:
    3. # ...
    4. App\HandlerCollection:
    5. # use getIndex() instead of getDefaultIndexName()
    6. arguments: [!tagged_iterator { tag: 'app.handler', default_index_method: 'getIndex' }]
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services
    6. https://symfony.com/schema/dic/services/services-1.0.xsd">
    7. <services>
    8. <!-- ... -->
    9. <service id="App\HandlerCollection">
    10. <!-- use getIndex() instead of getDefaultIndexName() -->
    11. <argument type="tagged_iterator"
    12. tag="app.handler"
    13. default-index-method="someFunctionName"
    14. />
    15. </service>
    16. </services>
    17. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use App\HandlerCollection;
    4. use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument;
    5. return function (ContainerConfigurator $configurator) {
    6. $services = $configurator->services();
    7. // ...
    8. // use getIndex() instead of getDefaultIndexName()
    9. $services->set(HandlerCollection::class)
    10. ->args([
    11. tagged_iterator('app.handler', null, 'getIndex'),
    12. ])
    13. ;
    14. };

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.