Defining Services Dependencies Automatically (Autowiring)

Defining Services Dependencies Automatically (Autowiring)

Autowiring allows you to manage services in the container with minimal configuration. It reads the type-hints on your constructor (or other methods) and automatically passes the correct services to each method. Symfony’s autowiring is designed to be predictable: if it is not absolutely clear which dependency should be passed, you’ll see an actionable exception.

Tip

Thanks to Symfony’s compiled container, there is no runtime overhead for using autowiring.

An Autowiring Example

Imagine you’re building an API to publish statuses on a Twitter feed, obfuscated with ROT13, a fun encoder that shifts all characters 13 letters forward in the alphabet.

Start by creating a ROT13 transformer class:

  1. // src/Util/Rot13Transformer.php
  2. namespace App\Util;
  3. class Rot13Transformer
  4. {
  5. public function transform(string $value): string
  6. {
  7. return str_rot13($value);
  8. }
  9. }

And now a Twitter client using this transformer:

  1. // src/Service/TwitterClient.php
  2. namespace App\Service;
  3. use App\Util\Rot13Transformer;
  4. // ...
  5. class TwitterClient
  6. {
  7. private $transformer;
  8. public function __construct(Rot13Transformer $transformer)
  9. {
  10. $this->transformer = $transformer;
  11. }
  12. public function tweet(User $user, string $key, string $status): void
  13. {
  14. $transformedStatus = $this->transformer->transform($status);
  15. // ... connect to Twitter and send the encoded status
  16. }
  17. }

If you’re using the default services.yaml configuration, both classes are automatically registered as services and configured to be autowired. This means you can use them immediately without any configuration.

However, to understand autowiring better, the following examples explicitly configure both services:

  • YAML

    1. # config/services.yaml
    2. services:
    3. _defaults:
    4. autowire: true
    5. autoconfigure: true
    6. # ...
    7. App\Service\TwitterClient:
    8. # redundant thanks to _defaults, but value is overridable on each service
    9. autowire: true
    10. App\Util\Rot13Transformer:
    11. autowire: true
  • 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 https://symfony.com/schema/dic/services/services-1.0.xsd">
    6. <services>
    7. <defaults autowire="true" autoconfigure="true"/>
    8. <!-- ... -->
    9. <!-- autowire is redundant thanks to defaults, but value is overridable on each service -->
    10. <service id="App\Service\TwitterClient" autowire="true"/>
    11. <service id="App\Util\Rot13Transformer" autowire="true"/>
    12. </services>
    13. </container>
  • PHP

    1. // config/services.php
    2. return function(ContainerConfigurator $configurator) {
    3. $services = $configurator->services()
    4. ->defaults()
    5. ->autowire()
    6. ->autoconfigure()
    7. ;
    8. $services->set(TwitterClient::class)
    9. // redundant thanks to defaults, but value is overridable on each service
    10. ->autowire();
    11. $services->set(Rot13Transformer::class)
    12. ->autowire();
    13. };

Now, you can use the TwitterClient service immediately in a controller:

  1. // src/Controller/DefaultController.php
  2. namespace App\Controller;
  3. use App\Service\TwitterClient;
  4. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\Routing\Annotation\Route;
  8. class DefaultController extends AbstractController
  9. {
  10. /**
  11. * @Route("/tweet", methods={"POST"})
  12. */
  13. public function tweet(TwitterClient $twitterClient, Request $request): Response
  14. {
  15. // fetch $user, $key, $status from the POST'ed data
  16. $twitterClient->tweet($user, $key, $status);
  17. // ...
  18. }
  19. }

This works automatically! The container knows to pass the Rot13Transformer service as the first argument when creating the TwitterClient service.

Autowiring Logic Explained

Autowiring works by reading the Rot13Transformer type-hint in TwitterClient:

  1. // src/Service/TwitterClient.php
  2. namespace App\Service;
  3. // ...
  4. use App\Util\Rot13Transformer;
  5. class TwitterClient
  6. {
  7. // ...
  8. public function __construct(Rot13Transformer $transformer)
  9. {
  10. $this->transformer = $transformer;
  11. }
  12. }

The autowiring system looks for a service whose id exactly matches the type-hint: so App\Util\Rot13Transformer. In this case, that exists! When you configured the Rot13Transformer service, you used its fully-qualified class name as its id. Autowiring isn’t magic: it looks for a service whose id matches the type-hint. If you load services automatically, each service’s id is its class name.

If there is not a service whose id exactly matches the type, a clear exception will be thrown.

Autowiring is a great way to automate configuration, and Symfony tries to be as predictable and clear as possible.

Using Aliases to Enable Autowiring

The main way to configure autowiring is to create a service whose id exactly matches its class. In the previous example, the service’s id is App\Util\Rot13Transformer, which allows us to autowire this type automatically.

This can also be accomplished using an alias. Suppose that for some reason, the id of the service was instead app.rot13.transformer. In this case, any arguments type-hinted with the class name (App\Util\Rot13Transformer) can no longer be autowired.

No problem! To fix this, you can create a service whose id matches the class by adding a service alias:

  • YAML

    1. # config/services.yaml
    2. services:
    3. # ...
    4. # the id is not a class, so it won't be used for autowiring
    5. app.rot13.transformer:
    6. class: App\Util\Rot13Transformer
    7. # ...
    8. # but this fixes it!
    9. # the ``app.rot13.transformer`` service will be injected when
    10. # an ``App\Util\Rot13Transformer`` type-hint is detected
    11. App\Util\Rot13Transformer: '@app.rot13.transformer'
  • 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 https://symfony.com/schema/dic/services/services-1.0.xsd">
    6. <services>
    7. <!-- ... -->
    8. <service id="app.rot13.transformer" class="App\Util\Rot13Transformer" autowire="true"/>
    9. <service id="App\Util\Rot13Transformer" alias="app.rot13.transformer"/>
    10. </services>
    11. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use App\Util\Rot13Transformer;
    4. return function(ContainerConfigurator $configurator) {
    5. // ...
    6. // the id is not a class, so it won't be used for autowiring
    7. $services->set('app.rot13.transformer', Rot13Transformer::class)
    8. ->autowire();
    9. // but this fixes it!
    10. // the ``app.rot13.transformer`` service will be injected when
    11. // an ``App\Util\Rot13Transformer`` type-hint is detected
    12. $services->alias(Rot13Transformer::class, 'app.rot13.transformer');
    13. };

This creates a service “alias”, whose id is App\Util\Rot13Transformer. Thanks to this, autowiring sees this and uses it whenever the Rot13Transformer class is type-hinted.

Tip

Aliases are used by the core bundles to allow services to be autowired. For example, MonologBundle creates a service whose id is logger. But it also adds an alias: Psr\Log\LoggerInterface that points to the logger service. This is why arguments type-hinted with Psr\Log\LoggerInterface can be autowired.

New in version 4.2: Since Monolog Bundle 3.5 each channel bind into container by type-hinted alias. More info in the part about how to autowire monolog channels.

Working with Interfaces

You might also find yourself type-hinting abstractions (e.g. interfaces) instead of concrete classes as it replaces your dependencies with other objects.

To follow this best practice, suppose you decide to create a TransformerInterface:

  1. // src/Util/TransformerInterface.php
  2. namespace App\Util;
  3. interface TransformerInterface
  4. {
  5. public function transform(string $value): string;
  6. }

Then, you update Rot13Transformer to implement it:

  1. // ...
  2. class Rot13Transformer implements TransformerInterface
  3. {
  4. // ...
  5. }

Now that you have an interface, you should use this as your type-hint:

  1. class TwitterClient
  2. {
  3. public function __construct(TransformerInterface $transformer)
  4. {
  5. // ...
  6. }
  7. // ...
  8. }

But now, the type-hint (App\Util\TransformerInterface) no longer matches the id of the service (App\Util\Rot13Transformer). This means that the argument can no longer be autowired.

To fix that, add an alias:

  • YAML

    1. # config/services.yaml
    2. services:
    3. # ...
    4. App\Util\Rot13Transformer: ~
    5. # the ``App\Util\Rot13Transformer`` service will be injected when
    6. # an ``App\Util\TransformerInterface`` type-hint is detected
    7. App\Util\TransformerInterface: '@App\Util\Rot13Transformer'
  • 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 https://symfony.com/schema/dic/services/services-1.0.xsd">
    6. <services>
    7. <!-- ... -->
    8. <service id="App\Util\Rot13Transformer"/>
    9. <service id="App\Util\TransformerInterface" alias="App\Util\Rot13Transformer"/>
    10. </services>
    11. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use App\Util\Rot13Transformer;
    4. use App\Util\TransformerInterface;
    5. return function(ContainerConfigurator $configurator) {
    6. // ...
    7. $services->set(Rot13Transformer::class);
    8. // the ``App\Util\Rot13Transformer`` service will be injected when
    9. // an ``App\Util\TransformerInterface`` type-hint is detected
    10. $services->alias(TransformerInterface::class, Rot13Transformer::class);
    11. };

Thanks to the App\Util\TransformerInterface alias, the autowiring subsystem knows that the App\Util\Rot13Transformer service should be injected when dealing with the TransformerInterface.

Tip

When using a service definition prototype, if only one service is discovered that implements an interface, and that interface is also discovered in the same file, configuring the alias is not mandatory and Symfony will automatically create one.

Dealing with Multiple Implementations of the Same Type

Suppose you create a second class - UppercaseTransformer that implements TransformerInterface:

  1. // src/Util/UppercaseTransformer.php
  2. namespace App\Util;
  3. class UppercaseTransformer implements TransformerInterface
  4. {
  5. public function transform(string $value): string
  6. {
  7. return strtoupper($value);
  8. }
  9. }

If you register this as a service, you now have two services that implement the App\Util\TransformerInterface type. Autowiring subsystem can not decide which one to use. Remember, autowiring isn’t magic; it looks for a service whose id matches the type-hint. So you need to choose one by creating an alias from the type to the correct service id (see Working with Interfaces). Additionally, you can define several named autowiring aliases if you want to use one implementation in some cases, and another implementation in some other cases.

For instance, you may want to use the Rot13Transformer implementation by default when the TransformerInterface interface is type hinted, but use the UppercaseTransformer implementation in some specific cases. To do so, you can create a normal alias from the TransformerInterface interface to Rot13Transformer, and then create a named autowiring alias from a special string containing the interface followed by a variable name matching the one you use when doing the injection:

  1. // src/Service/MastodonClient.php
  2. namespace App\Service;
  3. use App\Util\TransformerInterface;
  4. class MastodonClient
  5. {
  6. private $transformer;
  7. public function __construct(TransformerInterface $shoutyTransformer)
  8. {
  9. $this->transformer = $shoutyTransformer;
  10. }
  11. public function toot(User $user, string $key, string $status): void
  12. {
  13. $transformedStatus = $this->transformer->transform($status);
  14. // ... connect to Mastodon and send the transformed status
  15. }
  16. }
  • YAML

    1. # config/services.yaml
    2. services:
    3. # ...
    4. App\Util\Rot13Transformer: ~
    5. App\Util\UppercaseTransformer: ~
    6. # the ``App\Util\UppercaseTransformer`` service will be
    7. # injected when an ``App\Util\TransformerInterface``
    8. # type-hint for a ``$shoutyTransformer`` argument is detected.
    9. App\Util\TransformerInterface $shoutyTransformer: '@App\Util\UppercaseTransformer'
    10. # If the argument used for injection does not match, but the
    11. # type-hint still matches, the ``App\Util\Rot13Transformer``
    12. # service will be injected.
    13. App\Util\TransformerInterface: '@App\Util\Rot13Transformer'
    14. App\Service\TwitterClient:
    15. # the Rot13Transformer will be passed as the $transformer argument
    16. autowire: true
    17. # If you wanted to choose the non-default service and do not
    18. # want to use a named autowiring alias, wire it manually:
    19. # $transformer: '@App\Util\UppercaseTransformer'
    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 https://symfony.com/schema/dic/services/services-1.0.xsd">
    6. <services>
    7. <!-- ... -->
    8. <service id="App\Util\Rot13Transformer"/>
    9. <service id="App\Util\UppercaseTransformer"/>
    10. <service id="App\Util\TransformerInterface" alias="App\Util\Rot13Transformer"/>
    11. <service
    12. id="App\Util\TransformerInterface $shoutyTransformer"
    13. alias="App\Util\UppercaseTransformer"/>
    14. <service id="App\Service\TwitterClient" autowire="true">
    15. <!-- <argument key="$transformer" type="service" id="App\Util\UppercaseTransformer"/> -->
    16. </service>
    17. </services>
    18. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use App\Service\MastodonClient;
    4. use App\Service\TwitterClient;
    5. use App\Util\Rot13Transformer;
    6. use App\Util\TransformerInterface;
    7. use App\Util\UppercaseTransformer;
    8. return function(ContainerConfigurator $configurator) {
    9. // ...
    10. $services->set(Rot13Transformer::class)->autowire();
    11. $services->set(UppercaseTransformer::class)->autowire();
    12. // the ``App\Util\UppercaseTransformer`` service will be
    13. // injected when an ``App\Util\TransformerInterface``
    14. // type-hint for a ``$shoutyTransformer`` argument is detected.
    15. $services->alias(TransformerInterface::class.' $shoutyTransformer', UppercaseTransformer::class);
    16. // If the argument used for injection does not match, but the
    17. // type-hint still matches, the ``App\Util\Rot13Transformer``
    18. // service will be injected.
    19. $services->alias(TransformerInterface::class, Rot13Transformer::class);
    20. $services->set(TwitterClient::class)
    21. // the Rot13Transformer will be passed as the $transformer argument
    22. ->autowire()
    23. // If you wanted to choose the non-default service and do not
    24. // want to use a named autowiring alias, wire it manually:
    25. // ->arg('$transformer', ref(UppercaseTransformer::class))
    26. // ...
    27. ;
    28. };

Thanks to the App\Util\TransformerInterface alias, any argument type-hinted with this interface will be passed the App\Util\Rot13Transformer service. If the argument is named $shoutyTransformer, App\Util\UppercaseTransformer will be used instead. But, you can also manually wire any other service by specifying the argument under the arguments key.

New in version 4.2: Named autowiring aliases have been introduced in Symfony 4.2.

Fixing Non-Autowireable Arguments

Autowiring only works when your argument is an object. But if you have a scalar argument (e.g. a string), this cannot be autowired: Symfony will throw a clear exception.

To fix this, you can manually wire the problematic argument. You wire up the difficult arguments, Symfony takes care of the rest.

Autowiring other Methods (e.g. Setters)

When autowiring is enabled for a service, you can also configure the container to call methods on your class when it’s instantiated. For example, suppose you want to inject the logger service, and decide to use setter-injection:

  1. // src/Util/Rot13Transformer.php
  2. namespace App\Util;
  3. class Rot13Transformer
  4. {
  5. private $logger;
  6. /**
  7. * @required
  8. */
  9. public function setLogger(LoggerInterface $logger): void
  10. {
  11. $this->logger = $logger;
  12. }
  13. public function transform(string $value): string
  14. {
  15. $this->logger->info('Transforming '.$value);
  16. // ...
  17. }
  18. }

Autowiring will automatically call any method with the @required annotation above it, autowiring each argument. If you need to manually wire some of the arguments to a method, you can always explicitly configure the method call.

Autowiring Controller Action Methods

If you’re using the Symfony Framework, you can also autowire arguments to your controller action methods. This is a special case for autowiring, which exists for convenience. See Fetching Services for more details.

Performance Consequences

Thanks to Symfony’s compiled container, there is no performance penalty for using autowiring. However, there is a small performance penalty in the dev environment, as the container may be rebuilt more often as you modify classes. If rebuilding your container is slow (possible on very large projects), you may not be able to use autowiring.

Public and Reusable Bundles

Public bundles should explicitly configure their services and not rely on autowiring. Autowiring depends on the services that are available in the container and bundles have no control over the service container of applications they are included in. You can use autowiring when building reusable bundles within your company, as you have full control over all code.

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