English spoken conference

Symfony 5: The Fast Track

A new book to learn about developing modern Symfony 5 applications.

Support this project

You are browsing the Symfony 5.1 documentation, which changes significantly from Symfony 3.x. If your app doesn't use Symfony 5.1 yet, browse the Symfony 3.4 documentation.

Using a Factory to Create Services

Using a Factory to Create Services

Symfony's Service Container provides a powerful way of controlling the creation of objects, allowing you to specify arguments passed to the constructor as well as calling methods and setting parameters. Sometimes, however, this will not provide you with everything you need to construct your objects. For this situation, you can use a factory to create the object and tell the service container to call a method on the factory rather than directly instantiating the class.

Suppose you have a factory that configures and returns a new NewsletterManager object by calling the static createNewsletterManager() method:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class NewsletterManagerStaticFactory
{
    public static function createNewsletterManager()
    {
        $newsletterManager = new NewsletterManager();

        // ...

        return $newsletterManager;
    }
}

To make the NewsletterManager object available as a service, you can configure the service container to use the NewsletterManagerStaticFactory::createNewsletterManager() factory method:

  • YAML
    1
    2
    3
    4
    5
    6
    7
    # config/services.yaml
    services:
        # ...
    
        App\Email\NewsletterManager:
            # call the static method
            factory: ['App\Email\NewsletterManagerStaticFactory', 'createNewsletterManager']
    
  • XML
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    <!-- 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="App\Email\NewsletterManager">
                <!-- call the static method -->
                <factory class="App\Email\NewsletterManagerStaticFactory" method="createNewsletterManager"/>
    
                <!-- if the factory class is the same as the service class, you can omit
                     the 'class' attribute and define just the 'method' attribute:
    
                     <factory method="createNewsletterManager"/>
                -->
            </service>
        </services>
    </container>
    
  • PHP
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    // config/services.php
    namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    
    use App\Email\NewsletterManager;
    use App\Email\NewsletterManagerStaticFactory;
    
    return function(ContainerConfigurator $configurator) {
        $services = $configurator->services();
    
        // call the static method
        $services->set(NewsletterManager::class)
            ->factory([NewsletterManagerStaticFactory::class, 'createNewsletterManager']);
    };
    

Note

When using a factory to create services, the value chosen for class has no effect on the resulting service. The actual class name only depends on the object that is returned by the factory. However, the configured class name may be used by compiler passes and therefore should be set to a sensible value.

If your factory is not using a static function to configure and create your service, but a regular method, you can instantiate the factory itself as a service too. Later, in the "Passing Arguments to the Factory Method" section, you learn how you can inject arguments in this method.

Configuration of the service container then looks like this:

  • YAML
    1
    2
    3
    4
    5
    6
    7
    8
    9
    # config/services.yaml
    services:
        # ...
    
        App\Email\NewsletterManagerFactory: ~
    
        App\Email\NewsletterManager:
            # call a method on the specified factory service
            factory: ['@App\Email\NewsletterManagerFactory', 'createNewsletterManager']
    
  • XML
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    <!-- 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="App\Email\NewsletterManagerFactory"/>
    
            <service id="App\Email\NewsletterManager">
                <!-- call a method on the specified factory service -->
                <factory service="App\Email\NewsletterManagerFactory"
                    method="createNewsletterManager"
                />
            </service>
        </services>
    </container>
    
  • PHP
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    // config/services.php
    namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    
    use App\Email\NewsletterManager;
    use App\Email\NewsletterManagerFactory;
    
    return function(ContainerConfigurator $configurator) {
        $services = $configurator->services();
    
        $services->set(NewsletterManagerFactory::class);
    
        // call a method on the specified factory service
        $services->set(NewsletterManager::class)
            ->factory([ref(NewsletterManagerFactory::class), 'createNewsletterManager']);
    };
    

Suppose you now change your factory method to __invoke() so that your factory service can be used as a callback:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class InvokableNewsletterManagerFactory
{
    public function __invoke()
    {
        $newsletterManager = new NewsletterManager();

        // ...

        return $newsletterManager;
    }
}

Services can be created and configured via invokable factories by omitting the method name, just as routes can reference invokable controllers.

  • YAML
    1
    2
    3
    4
    5
    6
    7
    # config/services.yaml
    services:
        # ...
    
        App\Email\NewsletterManager:
            class:   App\Email\NewsletterManager
            factory: '@App\Email\NewsletterManagerFactory'
    
  • XML
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    <!-- 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="App\Email\NewsletterManager"
                     class="App\Email\NewsletterManager">
                <factory service="App\Email\NewsletterManagerFactory"/>
            </service>
        </services>
    </container>
    
  • PHP
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    // config/services.php
    namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    
    use App\Email\NewsletterManager;
    use App\Email\NewsletterManagerFactory;
    
    return function(ContainerConfigurator $configurator) {
        $services = $configurator->services();
    
        $services->set(NewsletterManager::class)
            ->args([ref('templating')])
            ->factory(ref(NewsletterManagerFactory::class));
    };
    

Passing Arguments to the Factory Method

Tip

Arguments to your factory method are autowired if that's enabled for your service.

If you need to pass arguments to the factory method you can use the arguments options. For example, suppose the createNewsletterManager() method in the previous example takes the templating service as an argument:

  • YAML
    1
    2
    3
    4
    5
    6
    7
    # config/services.yaml
    services:
        # ...
    
        App\Email\NewsletterManager:
            factory:   ['@App\Email\NewsletterManagerFactory', createNewsletterManager]
            arguments: ['@templating']
    
  • XML
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    <!-- 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="App\Email\NewsletterManager">
                <factory service="App\Email\NewsletterManagerFactory" method="createNewsletterManager"/>
                <argument type="service" id="templating"/>
            </service>
        </services>
    </container>
    
  • PHP
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    // config/services.php
    namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    
    use App\Email\NewsletterManager;
    use App\Email\NewsletterManagerFactory;
    
    return function(ContainerConfigurator $configurator) {
        $services = $configurator->services();
    
        $services->set(NewsletterManager::class)
            ->factory([ref(NewsletterManagerFactory::class), 'createNewsletterManager'])
            ->args([ref('templating')])
        ;
    };
    

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