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:

// src/Email/NewsletterManagerStaticFactory.php
namespace App\Email;

// ...

class NewsletterManagerStaticFactory
{
    public static function createNewsletterManager(): NewsletterManager
    {
        $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:

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:

Invokable Factories

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

// src/Email/InvokableNewsletterManagerFactory.php
namespace App\Email;

// ...
class InvokableNewsletterManagerFactory
{
    public function __invoke(): NewsletterManager
    {
        $newsletterManager = new NewsletterManager();

        // ...

        return $newsletterManager;
    }
}

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

Using Expressions in Service Factories

New in version 6.1: Using expressions as factories was introduced in Symfony 6.1.

Instead of using PHP classes as a factory, you can also use expressions. This allows you to e.g. change the service based on a parameter:

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: