Using a Factory to Create Services

Version: 2.5
Edit this page

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

Read the updated version of this page for Symfony 5.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:

1
2
3
4
5
6
7
8
9
10
11
class NewsletterManagerFactory
{
    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 NewsletterManagerFactory factory class:

  • YAML
  • XML
  • PHP
1
2
3
4
5
services:
    newsletter_manager:
        class:          NewsletterManager
        factory_class:  NewsletterManagerFactory
        factory_method: createNewsletterManager

When you specify the class to use for the factory (via factory_class) the method will be called statically. If the factory itself should be instantiated and the resulting object's method called, configure the factory itself as a service. In this case, the method (e.g. createNewsletterManager) should be changed to be non-static:

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
services:
    newsletter_manager_factory:
        class:            NewsletterManagerFactory
    newsletter_manager:
        class:            NewsletterManager
        factory_service:  newsletter_manager_factory
        factory_method:   createNewsletterManager

Note

The factory service is specified by its id name and not a reference to the service itself. So, you do not need to use the @ syntax for this in YAML configurations.

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:

  • YAML
  • XML
  • PHP
1
2
3
4
5
6
7
8
9
services:
    newsletter_manager_factory:
        class:            NewsletterManagerFactory
    newsletter_manager:
        class:            NewsletterManager
        factory_service:  newsletter_manager_factory
        factory_method:   createNewsletterManager
        arguments:
            - "@templating"
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.