How to Configure a Service with a Configurator

How to Configure a Service with a Configurator

The service configurator is a feature of the service container that allows you to use a callable to configure a service after its instantiation.

A service configurator can be used, for example, when you have a service that requires complex setup based on configuration settings coming from different sources/services. Using an external configurator, you can maintain the service implementation cleanly and keep it decoupled from the other objects that provide the configuration needed.

Another use case is when you have multiple objects that share a common configuration or that should be configured in a similar way at runtime.

For example, suppose you have an application where you send different types of emails to users. Emails are passed through different formatters that could be enabled or not depending on some dynamic application settings. You start defining a NewsletterManager class like this:

  1. // src/Mail/NewsletterManager.php
  2. namespace App\Mail;
  3. class NewsletterManager implements EmailFormatterAwareInterface
  4. {
  5. private $enabledFormatters;
  6. public function setEnabledFormatters(array $enabledFormatters): void
  7. {
  8. $this->enabledFormatters = $enabledFormatters;
  9. }
  10. // ...
  11. }

and also a GreetingCardManager class:

  1. // src/Mail/GreetingCardManager.php
  2. namespace App\Mail;
  3. class GreetingCardManager implements EmailFormatterAwareInterface
  4. {
  5. private $enabledFormatters;
  6. public function setEnabledFormatters(array $enabledFormatters): void
  7. {
  8. $this->enabledFormatters = $enabledFormatters;
  9. }
  10. // ...
  11. }

As mentioned before, the goal is to set the formatters at runtime depending on application settings. To do this, you also have an EmailFormatterManager class which is responsible for loading and validating formatters enabled in the application:

  1. // src/Mail/EmailFormatterManager.php
  2. namespace App\Mail;
  3. class EmailFormatterManager
  4. {
  5. // ...
  6. public function getEnabledFormatters(): array
  7. {
  8. // code to configure which formatters to use
  9. $enabledFormatters = [...];
  10. // ...
  11. return $enabledFormatters;
  12. }
  13. }

If your goal is to avoid having to couple NewsletterManager and GreetingCardManager with EmailFormatterManager, then you might want to create a configurator class to configure these instances:

  1. // src/Mail/EmailConfigurator.php
  2. namespace App\Mail;
  3. class EmailConfigurator
  4. {
  5. private $formatterManager;
  6. public function __construct(EmailFormatterManager $formatterManager)
  7. {
  8. $this->formatterManager = $formatterManager;
  9. }
  10. public function configure(EmailFormatterAwareInterface $emailManager): void
  11. {
  12. $emailManager->setEnabledFormatters(
  13. $this->formatterManager->getEnabledFormatters()
  14. );
  15. }
  16. // ...
  17. }

The EmailConfigurator’s job is to inject the enabled formatters into NewsletterManager and GreetingCardManager because they are not aware of where the enabled formatters come from. On the other hand, the EmailFormatterManager holds the knowledge about the enabled formatters and how to load them, keeping the single responsibility principle.

Tip

While this example uses a PHP class method, configurators can be any valid PHP callable, including functions, static methods and methods of services.

Using the Configurator

You can configure the service configurator using the configurator option. If you’re using the default services.yaml configuration, all the classes are already loaded as services. All you need to do is specify the configurator:

  • YAML

    1. # config/services.yaml
    2. services:
    3. # ...
    4. # Registers all 4 classes as services, including App\Mail\EmailConfigurator
    5. App\:
    6. resource: '../src/*'
    7. # ...
    8. # override the services to set the configurator
    9. App\Mail\NewsletterManager:
    10. configurator: ['@App\Mail\EmailConfigurator', 'configure']
    11. App\Mail\GreetingCardManager:
    12. configurator: ['@App\Mail\EmailConfigurator', 'configure']
  • 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. <prototype namespace="App\" resource="../src/*"/>
    9. <service id="App\Mail\NewsletterManager">
    10. <configurator service="App\Mail\EmailConfigurator" method="configure"/>
    11. </service>
    12. <service id="App\Mail\GreetingCardManager">
    13. <configurator service="App\Mail\EmailConfigurator" method="configure"/>
    14. </service>
    15. </services>
    16. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use App\Mail\EmailConfigurator;
    4. use App\Mail\GreetingCardManager;
    5. use App\Mail\NewsletterManager;
    6. return function(ContainerConfigurator $configurator) {
    7. $services = $configurator->services();
    8. // Registers all 4 classes as services, including App\Mail\EmailConfigurator
    9. $services->load('App\\', '../src/*');
    10. // override the services to set the configurator
    11. $services->set(NewsletterManager::class)
    12. ->configurator(ref(EmailConfigurator::class), 'configure');
    13. $services->set(GreetingCardManager::class)
    14. ->configurator(ref(EmailConfigurator::class), 'configure');
    15. };

New in version 4.3: Invokable configurators for services were introduced in Symfony 4.3.

Services can be configured via invokable configurators (replacing the configure() method with __invoke()) by omitting the method name:

  • YAML

    1. # config/services.yaml
    2. services:
    3. # ...
    4. # registers all classes as services, including App\Mail\EmailConfigurator
    5. App\:
    6. resource: '../src/*'
    7. # ...
    8. # override the services to set the configurator
    9. App\Mail\NewsletterManager:
    10. configurator: '@App\Mail\EmailConfigurator'
    11. App\Mail\GreetingCardManager:
    12. configurator: '@App\Mail\EmailConfigurator'
  • 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. <prototype namespace="App\" resource="../src/*"/>
    9. <service id="App\Mail\NewsletterManager">
    10. <configurator service="App\Mail\EmailConfigurator"/>
    11. </service>
    12. <service id="App\Mail\GreetingCardManager">
    13. <configurator service="App\Mail\EmailConfigurator"/>
    14. </service>
    15. </services>
    16. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use App\Mail\GreetingCardManager;
    4. use App\Mail\NewsletterManager;
    5. return function(ContainerConfigurator $configurator) {
    6. $services = $configurator->services();
    7. // Registers all 4 classes as services, including App\Mail\EmailConfigurator
    8. $services->load('App\\', '../src/*');
    9. // override the services to set the configurator
    10. $services->set(NewsletterManager::class)
    11. ->configurator(ref(EmailConfigurator::class));
    12. $services->set(GreetingCardManager::class)
    13. ->configurator(ref(EmailConfigurator::class));
    14. };

That’s it! When requesting the App\Mail\NewsletterManager or App\Mail\GreetingCardManager service, the created instance will first be passed to the EmailConfigurator::configure() method.

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