Symfony
sponsored by SensioLabs
Menu
  • About
  • Documentation
  • Screencasts
  • Cloud
  • Certification
  • Community
  • Businesses
  • News
  • Download
  1. Home
  2. Documentation
  3. Service Container
  4. How to Configure a Service with a Configurator
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud
Search by Algolia
  • Using the Configurator

How to Configure a Service with a Configurator

Edit this page

Warning: You are browsing the documentation for Symfony 3.3, which is no longer maintained.

Read the updated version of this page for Symfony 6.2 (the current stable version).

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
2
3
4
5
6
7
8
9
10
11
12
13
14
// src/AppBundle/Mail/NewsletterManager.php
namespace AppBundle\Mail;

class NewsletterManager implements EmailFormatterAwareInterface
{
    private $enabledFormatters;

    public function setEnabledFormatters(array $enabledFormatters)
    {
        $this->enabledFormatters = $enabledFormatters;
    }

    // ...
}

and also a GreetingCardManager class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// src/AppBundle/Mail/GreetingCardManager.php
namespace AppBundle\Mail;

class GreetingCardManager implements EmailFormatterAwareInterface
{
    private $enabledFormatters;

    public function setEnabledFormatters(array $enabledFormatters)
    {
        $this->enabledFormatters = $enabledFormatters;
    }

    // ...
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// src/AppBundle/Mail/EmailFormatterManager.php
namespace AppBundle\Mail;

class EmailFormatterManager
{
    // ...

    public function getEnabledFormatters()
    {
        // code to configure which formatters to use
        $enabledFormatters = array(...);

        // ...

        return $enabledFormatters;
    }
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// src/AppBundle/Mail/EmailConfigurator.php
namespace AppBundle\Mail;

class EmailConfigurator
{
    private $formatterManager;

    public function __construct(EmailFormatterManager $formatterManager)
    {
        $this->formatterManager = $formatterManager;
    }

    public function configure(EmailFormatterAwareInterface $emailManager)
    {
        $emailManager->setEnabledFormatters(
            $this->formatterManager->getEnabledFormatters()
        );
    }

    // ...
}

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.yml configuration, all the classes are already loaded as services. All you need to do is specify the configurator:

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# app/config/services.yml
services:
    # ...

    # Registers all 4 classes as services, including AppBundle\Mail\EmailConfigurator
    AppBundle\:
        resource: '../../src/AppBundle/*'
        # ...

    # override the services to set the configurator
    AppBundle\Mail\NewsletterManager:
        configurator: 'AppBundle\Mail\EmailConfigurator:configure'

    AppBundle\Mail\GreetingCardManager:
        configurator: 'AppBundle\Mail\EmailConfigurator:configure'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!-- app/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
        http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <prototype namespace="AppBundle\" resource="../../src/AppBundle/*" />

        <service id="AppBundle\Mail\NewsletterManager">
            <configurator service="AppBundle\Mail\EmailConfigurator" method="configure" />
        </service>

        <service id="AppBundle\Mail\GreetingCardManager">
            <configurator service="AppBundle\Mail\EmailConfigurator" method="configure" />
        </service>
    </services>
</container>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// app/config/services.php
use AppBundle\Mail\GreetingCardManager;
use AppBundle\Mail\NewsletterManager;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;

// Same as before
$definition = new Definition();

$definition->setAutowired(true);

$this->registerClasses($definition, 'AppBundle\\', '../../src/AppBundle/*');

$container->getDefinition(NewsletterManager::class)
    ->setConfigurator(array(new Reference(EmailConfigurator::class), 'configure'));

$container->getDefinition(GreetingCardManager::class)
    ->setConfigurator(array(new Reference(EmailConfigurator::class), 'configure'));

3.2

The service_id:method_name syntax for the YAML configuration format was introduced in Symfony 3.2.

The traditional configurator syntax in YAML files used an array to define the service id and the method name:

1
2
3
4
5
app.newsletter_manager:
    # new syntax
    configurator: 'AppBundle\Mail\EmailConfigurator:configure'
    # old syntax
    configurator: ['@AppBundle\Mail\EmailConfigurator', configure]

That's it! When requesting the AppBundle\Mail\NewsletterManager or AppBundle\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.
We stand with Ukraine.
Version:
Measure & Improve Symfony Code Performance

Measure & Improve Symfony Code Performance

Peruse our complete Symfony & PHP solutions catalog for your web development needs.

Peruse our complete Symfony & PHP solutions catalog for your web development needs.

↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

Avatar of Cyril Mouttet, a Symfony contributor

Thanks Cyril Mouttet (@placid2000) for being a Symfony contributor

1 commit • 2 lines changed

View all contributors that help us make Symfony

Become a Symfony contributor

Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

Learn how to contribute

Symfony™ is a trademark of Symfony SAS. All rights reserved.

  • What is Symfony?
    • Symfony at a Glance
    • Symfony Components
    • Case Studies
    • Symfony Releases
    • Security Policy
    • Logo & Screenshots
    • Trademark & Licenses
    • symfony1 Legacy
  • Learn Symfony
    • Symfony Docs
    • Symfony Book
    • Reference
    • Bundles
    • Best Practices
    • Training
    • eLearning Platform
    • Certification
  • Screencasts
    • Learn Symfony
    • Learn PHP
    • Learn JavaScript
    • Learn Drupal
    • Learn RESTful APIs
  • Community
    • SymfonyConnect
    • Support
    • How to be Involved
    • Code of Conduct
    • Events & Meetups
    • Projects using Symfony
    • Downloads Stats
    • Contributors
    • Backers
  • Blog
    • Events & Meetups
    • A week of symfony
    • Case studies
    • Cloud
    • Community
    • Conferences
    • Diversity
    • Documentation
    • Living on the edge
    • Releases
    • Security Advisories
    • SymfonyInsight
    • Twig
    • SensioLabs
  • Services
    • SensioLabs services
    • Train developers
    • Manage your project quality
    • Improve your project performance
    • Host Symfony projects
    Deployed on
Follow Symfony
Search by Algolia