Using a Factory to Create Services

Using a Factory to Create Services

Symfony’s Service Container provides multiple features to control the creation of objects, allowing you to specify arguments passed to the constructor as well as calling methods and setting parameters.

However, sometimes you need to apply the factory design pattern) to delegate the object creation to some special object called “the factory”. In those cases, the service container can call a method on your factory to create the object rather than directly instantiating the class.

Static Factories

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

  1. // src/Email\NewsletterManagerStaticFactory.php
  2. namespace App\Email;
  3. // ...
  4. class NewsletterManagerStaticFactory
  5. {
  6. public static function createNewsletterManager(): NewsletterManager
  7. {
  8. $newsletterManager = new NewsletterManager();
  9. // ...
  10. return $newsletterManager;
  11. }
  12. }

To make the NewsletterManager object available as a service, use the factory option to define which method of which class must be called to create its object:

  • YAML

    1. # config/services.yaml
    2. services:
    3. # ...
    4. App\Email\NewsletterManager:
    5. # the first argument is the class and the second argument is the static method
    6. factory: ['App\Email\NewsletterManagerStaticFactory', 'createNewsletterManager']
  • 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. <service id="App\Email\NewsletterManager">
    9. <!-- the first argument is the class and the second argument is the static method -->
    10. <factory class="App\Email\NewsletterManagerStaticFactory" method="createNewsletterManager"/>
    11. <!-- if the factory class is the same as the service class, you can omit
    12. the 'class' attribute and define just the 'method' attribute:
    13. <factory method="createNewsletterManager"/>
    14. -->
    15. </service>
    16. </services>
    17. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use App\Email\NewsletterManager;
    4. use App\Email\NewsletterManagerStaticFactory;
    5. return function(ContainerConfigurator $configurator) {
    6. $services = $configurator->services();
    7. $services->set(NewsletterManager::class)
    8. // the first argument is the class and the second argument is the static method
    9. ->factory([NewsletterManagerStaticFactory::class, 'createNewsletterManager']);
    10. };

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.

Non-Static Factories

If your factory is using a regular method instead of a static one to configure and create the service, instantiate the factory itself as a service too. Configuration of the service container then looks like this:

  • YAML

    1. # config/services.yaml
    2. services:
    3. # ...
    4. # first, create a service for the factory
    5. App\Email\NewsletterManagerFactory: ~
    6. # second, use the factory service as the first argument of the 'factory'
    7. # option and the factory method as the second argument
    8. App\Email\NewsletterManager:
    9. factory: ['@App\Email\NewsletterManagerFactory', 'createNewsletterManager']
  • 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. <!-- first, create a service for the factory -->
    9. <service id="App\Email\NewsletterManagerFactory"/>
    10. <!-- second, use the factory service as the first argument of the 'factory'
    11. option and the factory method as the second argument -->
    12. <service id="App\Email\NewsletterManager">
    13. <factory service="App\Email\NewsletterManagerFactory"
    14. method="createNewsletterManager"
    15. />
    16. </service>
    17. </services>
    18. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use App\Email\NewsletterManager;
    4. use App\Email\NewsletterManagerFactory;
    5. return function(ContainerConfigurator $configurator) {
    6. $services = $configurator->services();
    7. // first, create a service for the factory
    8. $services->set(NewsletterManagerFactory::class);
    9. // second, use the factory service as the first argument of the 'factory'
    10. // method and the factory method as the second argument
    11. $services->set(NewsletterManager::class)
    12. ->factory([ref(NewsletterManagerFactory::class), 'createNewsletterManager']);
    13. };

Invokable Factories

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

  1. // src/Email/InvokableNewsletterManagerFactory.php
  2. namespace App\Email;
  3. // ...
  4. class InvokableNewsletterManagerFactory
  5. {
  6. public function __invoke(): NewsletterManager
  7. {
  8. $newsletterManager = new NewsletterManager();
  9. // ...
  10. return $newsletterManager;
  11. }
  12. }

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

Services can be created and configured via invokable factories by omitting the method name:

  • YAML

    1. # config/services.yaml
    2. services:
    3. # ...
    4. App\Email\NewsletterManager:
    5. class: App\Email\NewsletterManager
    6. factory: '@App\Email\NewsletterManagerFactory'
  • 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. <!-- ... -->
    9. <service id="App\Email\NewsletterManager"
    10. class="App\Email\NewsletterManager">
    11. <factory service="App\Email\NewsletterManagerFactory"/>
    12. </service>
    13. </services>
    14. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use App\Email\NewsletterManager;
    4. use App\Email\NewsletterManagerFactory;
    5. return function(ContainerConfigurator $configurator) {
    6. $services = $configurator->services();
    7. $services->set(NewsletterManager::class)
    8. ->factory(ref(NewsletterManagerFactory::class));
    9. };

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 option. For example, suppose the createNewsletterManager() method in the previous examples takes the templating service as an argument:

  • YAML

    1. # config/services.yaml
    2. services:
    3. # ...
    4. App\Email\NewsletterManager:
    5. factory: ['@App\Email\NewsletterManagerFactory', createNewsletterManager]
    6. arguments: ['@templating']
  • 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. <!-- ... -->
    9. <service id="App\Email\NewsletterManager">
    10. <factory service="App\Email\NewsletterManagerFactory" method="createNewsletterManager"/>
    11. <argument type="service" id="templating"/>
    12. </service>
    13. </services>
    14. </container>
  • PHP

    1. // config/services.php
    2. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    3. use App\Email\NewsletterManager;
    4. use App\Email\NewsletterManagerFactory;
    5. return function(ContainerConfigurator $configurator) {
    6. $services = $configurator->services();
    7. $services->set(NewsletterManager::class)
    8. ->factory([ref(NewsletterManagerFactory::class), 'createNewsletterManager'])
    9. ->args([ref('templating')])
    10. ;
    11. };

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