Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • 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
    • SensioLabs Professional services to help you with Symfony
    • 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
  • Passing Arguments to the Factory Method

Using a Factory to Create Services

Edit this page

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

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

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:

1
2
3
4
5
6
7
# app/config/services.yml

services:
    app.newsletter_manager:
        class:   AppBundle\Email\NewsletterManager
        # call the static method
        factory: ['AppBundle\Email\NewsletterManagerStaticFactory', createNewsletterManager]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!-- 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>
        <service id="app.newsletter_manager" class="AppBundle\Email\NewsletterManager">
            <!-- call the static method -->
            <factory class="AppBundle\Email\NewsletterManagerStaticFactory" method="createNewsletterManager" />
        </service>
    </services>
</container>
1
2
3
4
5
6
7
8
9
// app/config/services.php

use AppBundle\Email\NewsletterManager;
use AppBundle\Email\NewsletterManagerStaticFactory;
// ...

$container->register('app.newsletter_manager', \AppBundle\NumberGenerator::class)
    // call the static method
    ->setFactory(array(NewsletterManagerStaticFactory::class, 'createNewsletterManager'));

Note

When using a factory to create services, the value chosen for the class option 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 "Using a Factory to Create Services" section, you learn how you can inject arguments in this method.

Configuration of the service container then looks like this:

1
2
3
4
5
6
7
8
9
10
# app/config/services.yml

services:
    app.newsletter_manager_factory:
        class: AppBundle\Email\NewsletterManagerFactory

    app.newsletter_manager:
        class:   AppBundle\Email\NewsletterManager
        # call a method on the specified factory service
        factory: 'app.newsletter_manager_factory:createNewsletterManager'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!-- 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>
        <service id="app.newsletter_manager_factory"
            class="AppBundle\Email\NewsletterManagerFactory"
        />

        <service id="app.newsletter_manager" class="AppBundle\Email\NewsletterManager">
            <!-- call a method on the specified factory service -->
            <factory service="app.newsletter_manager_factory"
                method="createNewsletterManager"
            />
        </service>
    </services>
</container>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// app/config/services.php

use AppBundle\Email\NewsletterManager;
use AppBundle\Email\NewsletterManagerFactory;
// ...

$container->register('app.newsletter_manager_factory', NewsletterManagerFactory::class);

$container->register('app.newsletter_manager', NewsletterManager::class)
    // call a method on the specified factory service
    ->setFactory(array(
        new Reference('app.newsletter_manager_factory'),
        'createNewsletterManager',
    ));

Note

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

1
2
3
4
5
6
7
# app/config/services.yml

app.newsletter_manager:
    # new syntax
    factory: 'app.newsletter_manager_factory:createNewsletterManager'
    # old syntax
    factory: ['@app.newsletter_manager_factory', createNewsletterManager]

Passing Arguments to the Factory Method

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

1
2
3
4
5
6
7
8
9
# app/config/services.yml

services:
    # ...

    app.newsletter_manager:
        class:     AppBundle\Email\NewsletterManager
        factory:   'newsletter_manager_factory:createNewsletterManager'
        arguments: ['@templating']
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!-- 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>
        <!-- ... -->

        <service id="app.newsletter_manager" class="AppBundle\Email\NewsletterManager">
            <factory service="app.newsletter_manager_factory" method="createNewsletterManager"/>
            <argument type="service" id="templating"/>
        </service>
    </services>
</container>
1
2
3
4
5
6
7
8
9
10
11
12
// app/config/services.php

use AppBundle\Email\NewsletterManager;
use Symfony\Component\DependencyInjection\Reference;

// ...
$container->register('app.newsletter_manager', NewsletterManager::class)
    ->addArgument(new Reference('templating'))
    ->setFactory(array(
        new Reference('app.newsletter_manager_factory'),
        'createNewsletterManager',
    ));
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version
    We stand with Ukraine.
    Version:
    Symfony Code Performance Profiling

    Symfony Code Performance Profiling

    Check Code Performance in Dev, Test, Staging & Production

    Check Code Performance in Dev, Test, Staging & Production

    Symfony footer

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

    Avatar of Sofien NAAS, a Symfony contributor

    Thanks Sofien NAAS for being a Symfony contributor

    1 commit • 36 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 Meilisearch