Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • SensioLabs Professional services to help you with Symfony
    • Platform.sh for Symfony Best platform to deploy Symfony apps
    • SymfonyInsight Automatic quality checks for your apps
    • Symfony Certification Prove your knowledge and boost your career
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by SensioLabs
  1. Home
  2. Documentation
  3. Service Container
  4. Using a Factory to Create Services
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud

Table of Contents

  • Static Factories
  • Non-Static Factories
  • Invokable Factories
  • Passing Arguments to the Factory Method

Using a Factory to Create Services

Edit this page

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

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

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
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, use the factory option to define which method of which class must be called to create its object:

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
# config/services.yaml
services:
    # ...

    App\Email\NewsletterManager:
        # the first argument is the class and the second argument is the static method
        factory: ['App\Email\NewsletterManagerStaticFactory', 'createNewsletterManager']
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">
            <!-- the first argument is the class and the second argument is 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>
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();

    $services->set(NewsletterManager::class)
        // the first argument is the class and the second argument is the static method
        ->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.

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
  • XML
  • PHP
1
2
3
4
5
6
7
8
9
10
11
# config/services.yaml
services:
    # ...

    # first, create a service for the factory
    App\Email\NewsletterManagerFactory: ~

    # second, use the factory service as the first argument of the 'factory'
    # option and the factory method as the second argument
    App\Email\NewsletterManager:
        factory: ['@App\Email\NewsletterManagerFactory', 'createNewsletterManager']
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>
        <!-- first, create a service for the factory -->
        <service id="App\Email\NewsletterManagerFactory"/>

        <!-- second, use the factory service as the first argument of the 'factory'
             option and the factory method as the second argument -->
        <service id="App\Email\NewsletterManager">
            <factory service="App\Email\NewsletterManagerFactory"
                method="createNewsletterManager"
            />
        </service>
    </services>
</container>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// config/services.php
namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use App\Email\NewsletterManager;
use App\Email\NewsletterManagerFactory;

return function(ContainerConfigurator $configurator) {
    $services = $configurator->services();

    // first, create a service for the factory
    $services->set(NewsletterManagerFactory::class);

    // second, use the factory service as the first argument of the 'factory'
    // method and the factory method as the second argument
    $services->set(NewsletterManager::class)
        ->factory([ref(NewsletterManagerFactory::class), 'createNewsletterManager']);
};

Invokable Factories

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;
    }
}

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, just as routes can reference invokable controllers.

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
# config/services.yaml
services:
    # ...

    App\Email\NewsletterManager:
        class:   App\Email\NewsletterManager
        factory: '@App\Email\NewsletterManagerFactory'
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>
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 option. For example, suppose the createNewsletterManager() method in the previous examples takes the templating service as an argument:

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
# config/services.yaml
services:
    # ...

    App\Email\NewsletterManager:
        factory:   ['@App\Email\NewsletterManagerFactory', createNewsletterManager]
        arguments: ['@templating']
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>
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.
TOC
    Version
    We stand with Ukraine.
    Version:
    Make sure your project is risk free

    Make sure your project is risk free

    Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).

    Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).

    Symfony footer

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

    Avatar of Michael Dowling, a Symfony contributor

    Thanks Michael Dowling (@mtdowling) for being a Symfony contributor

    1 commit • 21 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