Service Container

Screencast

Do you prefer video tutorials? Check out the Symfony Fundamentals screencast series.

Your application is full of useful objects: a "Mailer" object might help yousend emails while another object might help you save things to the database.Almost everything that your app "does" is actually done by one of these objects.And each time you install a new bundle, you get access to even more!

In Symfony, these useful objects are called services and each service livesinside a very special object called the service container. The containerallows you to centralize the way objects are constructed. It makes your lifeeasier, promotes a strong architecture and is super fast!

Fetching and using Services

The moment you start a Symfony app, your container already contains many services.These are like tools: waiting for you to take advantage of them. In your controller,you can "ask" for a service from the container by type-hinting an argument with theservice's class or interface name. Want to log something? No problem:

  1. // src/Controller/ProductController.php
  2. // ...
  3.  
  4. use Psr\Log\LoggerInterface;
  5.  
  6. /**
  7. * @Route("/products")
  8. */
  9. public function list(LoggerInterface $logger)
  10. {
  11. $logger->info('Look! I just used a service');
  12.  
  13. // ...
  14. }

What other services are available? Find out by running:

  1. $ php bin/console debug:autowiring
  2.  
  3. # this is just a *small* sample of the output...
  4.  
  5. Describes a logger instance.
  6. Psr\Log\LoggerInterface (monolog.logger)
  7.  
  8. Request stack that controls the lifecycle of requests.
  9. Symfony\Component\HttpFoundation\RequestStack (request_stack)
  10.  
  11. Interface for the session.
  12. Symfony\Component\HttpFoundation\Session\SessionInterface (session)
  13.  
  14. RouterInterface is the interface that all Router classes must implement.
  15. Symfony\Component\Routing\RouterInterface (router.default)
  16.  
  17. [...]

When you use these type-hints in your controller methods or inside yourown services, Symfony will automaticallypass you the service object matching that type.

Throughout the docs, you'll see how to use the many different services that livein the container.

Tip

There are actually many more services in the container, and each service hasa unique id in the container, like session or router.default. For a fulllist, you can run php bin/console debug:container. But most of the time,you won't need to worry about this. See Choose a Specific Service.See How to Debug the Service Container & List Services.

Creating/Configuring Services in the Container

You can also organize your own code into services. For example, suppose you needto show your users a random, happy message. If you put this code in your controller,it can't be re-used. Instead, you decide to create a new class:

  1. // src/Service/MessageGenerator.php
  2. namespace App\Service;
  3.  
  4. class MessageGenerator
  5. {
  6. public function getHappyMessage()
  7. {
  8. $messages = [
  9. 'You did it! You updated the system! Amazing!',
  10. 'That was one of the coolest updates I\'ve seen all day!',
  11. 'Great work! Keep going!',
  12. ];
  13.  
  14. $index = array_rand($messages);
  15.  
  16. return $messages[$index];
  17. }
  18. }

Congratulations! You've just created your first service class! You can use it immediatelyinside your controller:

  1. use App\Service\MessageGenerator;
  2.  
  3. public function new(MessageGenerator $messageGenerator)
  4. {
  5. // thanks to the type-hint, the container will instantiate a
  6. // new MessageGenerator and pass it to you!
  7. // ...
  8.  
  9. $message = $messageGenerator->getHappyMessage();
  10. $this->addFlash('success', $message);
  11. // ...
  12. }

When you ask for the MessageGenerator service, the container constructs a newMessageGenerator object and returns it (see sidebar below). But if you never askfor the service, it's never constructed: saving memory and speed. As a bonus, theMessageGenerator service is only created once: the same instance is returnedeach time you ask for it.

Automatic Service Loading in services.yaml

The documentation assumes you're using the following service configuration,which is the default config for a new project:

  • YAML
  1. # config/services.yaml
  2. services:
  3. # default configuration for services in *this* file
  4. _defaults:
  5. autowire: true # Automatically injects dependencies in your services.
  6. autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
  7. public: false # Allows optimizing the container by removing unused services; this also means
  8. # fetching services directly from the container via $container->get() won't work.
  9. # The best practice is to be explicit about your dependencies anyway.
  10.  
  11. # makes classes in src/ available to be used as services
  12. # this creates a service per class whose id is the fully-qualified class name
  13. App\:
  14. resource: '../src/*'
  15. exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'
  16.  
  17. # ...
  • 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.  
  8. <services>
  9. <!-- Default configuration for services in *this* file -->
  10. <defaults autowire="true" autoconfigure="true" public="false"/>
  11.  
  12. <prototype namespace="App\" resource="../src/*" exclude="../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}"/>
  13. </services>
  14. </container>
  • PHP
  1. // config/services.php
  2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
  3.  
  4. return function(ContainerConfigurator $configurator) {
  5. // default configuration for services in *this* file
  6. $services = $configurator->services()
  7. ->defaults()
  8. ->autowire() // Automatically injects dependencies in your services.
  9. ->autoconfigure() // Automatically registers your services as commands, event subscribers, etc.
  10. ;
  11.  
  12. // makes classes in src/ available to be used as services
  13. // this creates a service per class whose id is the fully-qualified class name
  14. $services->load('App\\', '../src/*')
  15. ->exclude('../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}');
  16. };

Tip

The value of the resource and exclude options can be any validglob pattern). The value of the exclude option can also be anarray of glob patterns.

Thanks to this configuration, you can automatically use any classes from thesrc/ directory as a service, without needing to manually configureit. Later, you'll learn more about this in Importing Many Services at once with resource.

If you'd prefer to manually wire your service, that's totally possible: seeExplicitly Configuring Services and Arguments.

Injecting Services/Config into a Service

What if you need to access the logger service from within MessageGenerator?No problem! Create a __construct() method with a $logger argument that hasthe LoggerInterface type-hint. Set this on a new $logger propertyand use it later:

  1. // src/Service/MessageGenerator.php
  2. // ...
  3.  
  4. use Psr\Log\LoggerInterface;
  5.  
  6. class MessageGenerator
  7. {
  8. private $logger;
  9.  
  10. public function __construct(LoggerInterface $logger)
  11. {
  12. $this->logger = $logger;
  13. }
  14.  
  15. public function getHappyMessage()
  16. {
  17. $this->logger->info('About to find a happy message!');
  18. // ...
  19. }
  20. }

That's it! The container will automatically know to pass the logger servicewhen instantiating the MessageGenerator. How does it know to do this?Autowiring. The key is the LoggerInterfacetype-hint in your __construct() method and the autowire: true config inservices.yaml. When you type-hint an argument, the container will automaticallyfind the matching service. If it can't, you'll see a clear exception with a helpfulsuggestion.

By the way, this method of adding dependencies to your _construct() method iscalled _dependency injection. It's a scary term for a simple concept.

How should you know to use LoggerInterface for the type-hint? You can eitherread the docs for whatever feature you're using, or get a list of autowireabletype-hints by running:

  1. $ php bin/console debug:autowiring
  2.  
  3. # this is just a *small* sample of the output...
  4.  
  5. Describes a logger instance.
  6. Psr\Log\LoggerInterface (monolog.logger)
  7.  
  8. Request stack that controls the lifecycle of requests.
  9. Symfony\Component\HttpFoundation\RequestStack (request_stack)
  10.  
  11. Interface for the session.
  12. Symfony\Component\HttpFoundation\Session\SessionInterface (session)
  13.  
  14. RouterInterface is the interface that all Router classes must implement.
  15. Symfony\Component\Routing\RouterInterface (router.default)
  16.  
  17. [...]

Handling Multiple Services

Suppose you also want to email a site administrator each time a site update ismade. To do that, you create a new class:

  1. // src/Updates/SiteUpdateManager.php
  2. namespace App\Updates;
  3.  
  4. use App\Service\MessageGenerator;
  5.  
  6. class SiteUpdateManager
  7. {
  8. private $messageGenerator;
  9. private $mailer;
  10.  
  11. public function __construct(MessageGenerator $messageGenerator, \Swift_Mailer $mailer)
  12. {
  13. $this->messageGenerator = $messageGenerator;
  14. $this->mailer = $mailer;
  15. }
  16.  
  17. public function notifyOfSiteUpdate()
  18. {
  19. $happyMessage = $this->messageGenerator->getHappyMessage();
  20.  
  21. $message = (new \Swift_Message('Site update just happened!'))
  22. ->setFrom('[email protected]')
  23. ->setTo('[email protected]')
  24. ->addPart(
  25. 'Someone just updated the site. We told them: '.$happyMessage
  26. );
  27.  
  28. return $this->mailer->send($message) > 0;
  29. }
  30. }

This needs the MessageGenerator and the Swift_Mailer service. That's noproblem! In fact, this new service is ready to be used. In a controller, for example,you can type-hint the new SiteUpdateManager class and use it:

  1. // src/Controller/SiteController.php
  2.  
  3. // ...
  4. use App\Updates\SiteUpdateManager;
  5.  
  6. public function new(SiteUpdateManager $siteUpdateManager)
  7. {
  8. // ...
  9.  
  10. if ($siteUpdateManager->notifyOfSiteUpdate()) {
  11. $this->addFlash('success', 'Notification mail was sent successfully.');
  12. }
  13.  
  14. // ...
  15. }

Thanks to autowiring and your type-hints in __construct(), the container createsthe SiteUpdateManager object and passes it the correct argument. In most cases,this works perfectly.

Manually Wiring Arguments

But there are a few cases when an argument to a service cannot be autowired. Forexample, suppose you want to make the admin email configurable:

  1. // src/Updates/SiteUpdateManager.php
  2. // ...
  3.  
  4. class SiteUpdateManager
  5. {
  6. // ...
  7. + private $adminEmail;
  8.  
  9. - public function __construct(MessageGenerator $messageGenerator, \Swift_Mailer $mailer)
  10. + public function __construct(MessageGenerator $messageGenerator, \Swift_Mailer $mailer, $adminEmail)
  11. {
  12. // ...
  13. + $this->adminEmail = $adminEmail;
  14. }
  15.  
  16. public function notifyOfSiteUpdate()
  17. {
  18. // ...
  19.  
  20. $message = \Swift_Message::newInstance()
  21. // ...
  22. - ->setTo('[email protected]')
  23. + ->setTo($this->adminEmail)
  24. // ...
  25. ;
  26. // ...
  27. }
  28. }

If you make this change and refresh, you'll see an error:

Cannot autowire service "AppUpdatesSiteUpdateManager": argument "$adminEmail"of method "__construct()" must have a type-hint or be given a value explicitly.

That makes sense! There is no way that the container knows what value you want topass here. No problem! In your configuration, you can explicitly set this argument:

  • YAML
  1. # config/services.yaml
  2. services:
  3. # ...
  4.  
  5. # same as before
  6. App\:
  7. resource: '../src/*'
  8. exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'
  9.  
  10. # explicitly configure the service
  11. App\Updates\SiteUpdateManager:
  12. arguments:
  13. $adminEmail: '[email protected]'
  • 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.  
  8. <services>
  9. <!-- ... -->
  10.  
  11. <!-- Same as before -->
  12.  
  13. <prototype namespace="App\" resource="../src/*" exclude="../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}"/>
  14.  
  15. <!-- Explicitly configure the service -->
  16. <service id="App\Updates\SiteUpdateManager">
  17. <argument key="$adminEmail">[email protected]</argument>
  18. </service>
  19. </services>
  20. </container>
  • PHP
  1. // config/services.php
  2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
  3.  
  4. use App\Updates\SiteUpdateManager;
  5.  
  6. return function(ContainerConfigurator $configurator) {
  7. // ...
  8.  
  9. // same as before
  10. $services->load('App\\', '../src/*')
  11. ->exclude('../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}');
  12.  
  13. $services->set(SiteUpdateManager::class)
  14. ->arg('$adminEmail', '[email protected]')
  15. ;
  16. };

Thanks to this, the container will pass manager@example.com to the $adminEmailargument of __construct when creating the SiteUpdateManager service. Theother arguments will still be autowired.

But, isn't this fragile? Fortunately, no! If you rename the $adminEmail argumentto something else - e.g. $mainEmail - you will get a clear exception when youreload the next page (even if that page doesn't use this service).

Service Parameters

In addition to holding service objects, the container also holds configuration,called parameters. The main article about Symfony configuration explains theconfiguration parameters in detail and showsall their types (string, boolean, array, binary and PHP constant parameters).

However, there is another type of parameter related to services. In YAML config,any string which starts with @ is considered as the ID of a service, insteadof a regular string. In XML config, use the type="service" type for theparameter and in PHP config use the Reference class:

  • YAML
  1. # config/services.yaml
  2. services:
  3. App\Service\MessageGenerator:
  4. # this is not a string, but a reference to a service called 'logger'
  5. arguments: ['@logger']
  6.  
  7. # if the value of a string parameter starts with '@', you need to escape
  8. # it by adding another '@' so Symfony doesn't consider it a service
  9. # (this will be parsed as the string '@securepassword')
  10. mailer_password: '@@securepassword'
  • 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.  
  8. <services>
  9. <service id="App\Service\MessageGenerator">
  10. <argument type="service" id="logger"/>
  11. </service>
  12. </services>
  13. </container>
  • PHP
  1. // config/services.php
  2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
  3.  
  4. use App\Service\MessageGenerator;
  5.  
  6. return function(ContainerConfigurator $configurator) {
  7. $services = $configurator->services();
  8.  
  9. $services->set(MessageGenerator::class)
  10. ->args([ref('logger')])
  11. ;
  12. };

Working with container parameters is straightforward using the container'saccessor methods for parameters:

  1. // checks if a parameter is defined (parameter names are case-sensitive)
  2. $container->hasParameter('mailer.transport');
  3.  
  4. // gets value of a parameter
  5. $container->getParameter('mailer.transport');
  6.  
  7. // adds a new parameter
  8. $container->setParameter('mailer.transport', 'sendmail');

Caution

The used . notation is aSymfony convention to make parameterseasier to read. Parameters are flat key-value elements, they can'tbe organized into a nested array

Note

You can only set a parameter before the container is compiled, not at run-time.To learn more about compiling the container seeCompiling the Container.

Choose a Specific Service

The MessageGenerator service created earlier requires a LoggerInterface argument:

  1. // src/Service/MessageGenerator.php
  2. // ...
  3.  
  4. use Psr\Log\LoggerInterface;
  5.  
  6. class MessageGenerator
  7. {
  8. private $logger;
  9.  
  10. public function __construct(LoggerInterface $logger)
  11. {
  12. $this->logger = $logger;
  13. }
  14. // ...
  15. }

However, there are multiple services in the container that implement LoggerInterface,such as logger, monolog.logger.request, monolog.logger.php, etc. Howdoes the container know which one to use?

In these situations, the container is usually configured to automatically chooseone of the services - logger in this case (read more about why in Using Aliases to Enable Autowiring).But, you can control this and pass in a different logger:

  • YAML
  1. # config/services.yaml
  2. services:
  3. # ... same code as before
  4.  
  5. # explicitly configure the service
  6. App\Service\MessageGenerator:
  7. arguments:
  8. # the '@' symbol is important: that's what tells the container
  9. # you want to pass the *service* whose id is 'monolog.logger.request',
  10. # and not just the *string* 'monolog.logger.request'
  11. $logger: '@monolog.logger.request'
  • 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.  
  8. <services>
  9. <!-- ... same code as before -->
  10.  
  11. <!-- Explicitly configure the service -->
  12. <service id="App\Service\MessageGenerator">
  13. <argument key="$logger" type="service" id="monolog.logger.request"/>
  14. </service>
  15. </services>
  16. </container>
  • PHP
  1. // config/services.php
  2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
  3.  
  4. use App\Service\MessageGenerator;
  5.  
  6. return function(ContainerConfigurator $configurator) {
  7. // ... same code as before
  8.  
  9. // explicitly configure the service
  10. $services->set(SiteUpdateManager::class)
  11. ->arg('$logger', ref('monolog.logger.request'))
  12. ;
  13. };

This tells the container that the $logger argument to __construct should useservice whose id is monolog.logger.request.

For a full list of all possible services in the container, run:

  1. $ php bin/console debug:container

Binding Arguments by Name or Type

You can also use the bind keyword to bind specific arguments by name or type:

  • YAML
  1. # config/services.yaml
  2. services:
  3. _defaults:
  4. bind:
  5. # pass this value to any $adminEmail argument for any service
  6. # that's defined in this file (including controller arguments)
  7. $adminEmail: '[email protected]'
  8.  
  9. # pass this service to any $requestLogger argument for any
  10. # service that's defined in this file
  11. $requestLogger: '@monolog.logger.request'
  12.  
  13. # pass this service for any LoggerInterface type-hint for any
  14. # service that's defined in this file
  15. Psr\Log\LoggerInterface: '@monolog.logger.request'
  16.  
  17. # optionally you can define both the name and type of the argument to match
  18. string $adminEmail: '[email protected]'
  19. Psr\Log\LoggerInterface $requestLogger: '@monolog.logger.request'
  20.  
  21. # ...
  • 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.  
  8. <services>
  9. <defaults autowire="true" autoconfigure="true" public="false">
  10. <bind key="$adminEmail">[email protected]</bind>
  11. <bind key="$requestLogger"
  12. type="service"
  13. id="monolog.logger.request"
  14. />
  15. <bind key="Psr\Log\LoggerInterface"
  16. type="service"
  17. id="monolog.logger.request"
  18. />
  19.  
  20. <!-- optionally you can define both the name and type of the argument to match -->
  21. <bind key="string $adminEmail">[email protected]</bind>
  22. <bind key="Psr\Log\LoggerInterface $requestLogger"
  23. type="service"
  24. id="monolog.logger.request"
  25. />
  26. </defaults>
  27.  
  28. <!-- ... -->
  29. </services>
  30. </container>
  • PHP
  1. // config/services.php
  2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
  3.  
  4. use App\Controller\LuckyController;
  5. use Psr\Log\LoggerInterface;
  6. use Symfony\Component\DependencyInjection\Reference;
  7.  
  8. return function(ContainerConfigurator $configurator) {
  9. $services = $configurator->services()
  10. ->defaults()
  11. // pass this value to any $adminEmail argument for any service
  12. // that's defined in this file (including controller arguments)
  13. ->bind('$adminEmail', '[email protected]')
  14.  
  15. // pass this service to any $requestLogger argument for any
  16. // service that's defined in this file
  17. ->bind('$requestLogger', ref('monolog.logger.request'))
  18.  
  19. // pass this service for any LoggerInterface type-hint for any
  20. // service that's defined in this file
  21. ->bind(LoggerInterface::class, ref('monolog.logger.request'))
  22.  
  23. // optionally you can define both the name and type of the argument to match
  24. ->bind('string $adminEmail', '[email protected]')
  25. ->bind(LoggerInterface::class.' $requestLogger', ref('monolog.logger.request'))
  26. ;
  27.  
  28. // ...
  29. };

By putting the bind key under defaults, you can specify the value of _any_argument for _any service defined in this file! You can bind arguments by name(e.g. $adminEmail), by type (e.g. Psr\Log\LoggerInterface) or both(e.g. Psr\Log\LoggerInterface $requestLogger).

The bind config can also be applied to specific services or when loading manyservices at once (i.e. Importing Many Services at once with resource).

The autowire Option

Above, the services.yaml file has autowire: true in the _defaults sectionso that it applies to all services defined in that file. With this setting, you'reable to type-hint arguments in the __construct() method of your services andthe container will automatically pass you the correct arguments. This entire entryhas been written around autowiring.

For more details about autowiring, check out Defining Services Dependencies Automatically (Autowiring).

The autoconfigure Option

Above, the services.yaml file has autoconfigure: true in the defaultssection so that it applies to all services defined in that file. With this setting,the container will automatically apply certain configuration to your services, basedon your service's _class. This is mostly used to auto-tag your services.

For example, to create a Twig extension, you need to create a class, register itas a service, and tag it with twig.extension.

But, with autoconfigure: true, you don't need the tag. In fact, if you're usingthe default services.yaml config,you don't need to do anything: the service will be automatically loaded. Then,autoconfigure will add the twig.extension tag for you, because your classimplements Twig\Extension\ExtensionInterface. And thanks to autowire, you can even addconstructor arguments without any configuration.

Public Versus Private Services

Thanks to the _defaults section in services.yaml, every service defined inthis file is public: false by default.

What does this mean? When a service is public, you can access it directlyfrom the container object, which is accessible from any controller that extendsController:

  1. use App\Service\MessageGenerator;
  2.  
  3. // ...
  4. public function new()
  5. {
  6. // there IS a public "logger" service in the container
  7. $logger = $this->container->get('logger');
  8.  
  9. // this will NOT work: MessageGenerator is a private service
  10. $generator = $this->container->get(MessageGenerator::class);
  11. }

As a best practice, you should only create private services, which will happenautomatically. And also, you should not use the $container->get() method tofetch public services.

But, if you do need to make a service public, override the public setting:

  • YAML
  1. # config/services.yaml
  2. services:
  3. # ... same code as before
  4.  
  5. # explicitly configure the service
  6. App\Service\MessageGenerator:
  7. public: 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
  6. https://symfony.com/schema/dic/services/services-1.0.xsd">
  7.  
  8. <services>
  9. <!-- ... same code as before -->
  10.  
  11. <!-- Explicitly configure the service -->
  12. <service id="App\Service\MessageGenerator" public="true"></service>
  13. </services>
  14. </container>
  • PHP
  1. // config/services.php
  2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
  3.  
  4. use App\Service\MessageGenerator;
  5.  
  6. return function(ContainerConfigurator $configurator) {
  7. // ... same as code before
  8.  
  9. // explicitly configure the service
  10. $services->set(MessageGenerator::class)
  11. ->public()
  12. ;
  13. };

Importing Many Services at once with resource

You've already seen that you can import many services at once by using the resourcekey. For example, the default Symfony configuration contains this:

  • YAML
  1. # config/services.yaml
  2. services:
  3. # ...
  4.  
  5. # makes classes in src/ available to be used as services
  6. # this creates a service per class whose id is the fully-qualified class name
  7. App\:
  8. resource: '../src/*'
  9. exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'
  • 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.  
  8. <services>
  9. <!-- ... -->
  10.  
  11. <prototype namespace="App\" resource="../src/*" exclude="../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}"/>
  12. </services>
  13. </container>
  • PHP
  1. // config/services.php
  2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
  3.  
  4. return function(ContainerConfigurator $configurator) {
  5. // ...
  6.  
  7. // makes classes in src/ available to be used as services
  8. // this creates a service per class whose id is the fully-qualified class name
  9. $services->load('App\\', '../src/*')
  10. ->exclude('../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}');
  11. };

Tip

The value of the resource and exclude options can be any validglob pattern).

This can be used to quickly make many classes available as services and apply somedefault configuration. The id of each service is its fully-qualified class name.You can override any service that's imported by using its id (class name) below(e.g. see Manually Wiring Arguments). If you override a service, none ofthe options (e.g. public) are inherited from the import (but the overriddenservice does still inherit from _defaults).

You can also exclude certain paths. This is optional, but will slightly increaseperformance in the dev environment: excluded paths are not tracked and so modifyingthem will not cause the container to be rebuilt.

Note

Wait, does this mean that every class in src/ is registered asa service? Even model classes? Actually, no. As long as you havepublic: false under your defaults key (or you can add it under thespecific import), all the imported services are _private. Thanks to this, allclasses in src/ that are not explicitly used as services areautomatically removed from the final container. In reality, the importmeans that all classes are "available to be used as services" without needingto be manually configured.

Multiple Service Definitions Using the Same Namespace

If you define services using the YAML config format, the PHP namespace is usedas the key of each configuration, so you can't define different service configsfor classes under the same namespace:

  1. # config/services.yaml
  2. services:
  3. App\Domain\:
  4. resource: '../src/Domain/*'
  5. # ...

In order to have multiple definitions, add the namespace option and use anyunique string as the key of each service config:

  1. # config/services.yaml
  2. services:
  3. command_handlers:
  4. namespace: App\Domain\
  5. resource: '../src/Domain/*/CommandHandler'
  6. tags: [command_handler]
  7.  
  8. event_subscribers:
  9. namespace: App\Domain\
  10. resource: '../src/Domain/*/EventSubscriber'
  11. tags: [event_subscriber]

Explicitly Configuring Services and Arguments

Prior to Symfony 3.3, all services and (typically) arguments were explicitly configured:it was not possible to load services automaticallyand autowiring was much less common.

Both of these features are optional. And even if you use them, there may be somecases where you want to manually wire a service. For example, suppose that you wantto register 2 services for the SiteUpdateManager class - each with a differentadmin email. In this case, each needs to have a unique service id:

  • YAML
  1. # config/services.yaml
  2. services:
  3. # ...
  4.  
  5. # this is the service's id
  6. site_update_manager.superadmin:
  7. class: App\Updates\SiteUpdateManager
  8. # you CAN still use autowiring: we just want to show what it looks like without
  9. autowire: false
  10. # manually wire all arguments
  11. arguments:
  12. - '@App\Service\MessageGenerator'
  13. - '@mailer'
  14. - '[email protected]'
  15.  
  16. site_update_manager.normal_users:
  17. class: App\Updates\SiteUpdateManager
  18. autowire: false
  19. arguments:
  20. - '@App\Service\MessageGenerator'
  21. - '@mailer'
  22. - '[email protected]'
  23.  
  24. # Create an alias, so that - by default - if you type-hint SiteUpdateManager,
  25. # the site_update_manager.superadmin will be used
  26. App\Updates\SiteUpdateManager: '@site_update_manager.superadmin'
  • XML
<!-- config/services.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<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">

    <services>
        <!-- ... -->

        <service id="site_update_manager.superadmin" class="App\Updates\SiteUpdateManager" autowire="false">
            <argument type="service" id="App\Service\MessageGenerator"/>
            <argument type="service" id="mailer"/>
            <argument>[email protected]</argument>
        </service>

        <service id="site_update_manager.normal_users" class="App\Updates\SiteUpdateManager" autowire="false">
            <argument type="service" id="App\Service\MessageGenerator"/>
            <argument type="service" id="mailer"/>
            <argument>[email protected]</argument>
        </service>

        <service id="App\Updates\SiteUpdateManager" alias="site_update_manager.superadmin"/>
    </services>
</container>
  • PHP
// config/services.php
namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use App\Service\MessageGenerator;
use App\Updates\SiteUpdateManager;

return function(ContainerConfigurator $configurator) {
    // ...

    // site_update_manager.superadmin is the service's id
    $services->set('site_update_manager.superadmin', SiteUpdateManager::class)
        // you CAN still use autowiring: we just want to show what it looks like without
        ->autowire(false)
        // manually wire all arguments
        ->args([
            ref(MessageGenerator::class),
            ref('mailer'),
            '[email protected]',
        ]);

    $services->set('site_update_manager.normal_users', SiteUpdateManager::class)
        ->autowire(false)
        ->args([
            ref(MessageGenerator::class),
            ref('mailer'),
            '[email protected]',
        ]);

    // Create an alias, so that - by default - if you type-hint SiteUpdateManager,
    // the site_update_manager.superadmin will be used
    $services->alias(SiteUpdateManager::class, 'site_update_manager.superadmin');
};

In this case, two services are registered: site_update_manager.superadminand site_update_manager.normal_users. Thanks to the alias, if you type-hintSiteUpdateManager the first (site_update_manager.superadmin) will be passed.If you want to pass the second, you'll need to manually wire the service.

Caution

If you do not create the alias and are loading all services from src/,then three services have been created (the automatic service + your two services)and the automatically loaded service will be passed - by default - when you type-hintSiteUpdateManager. That's why creating the alias is a good idea.

Learn more