Using a Factory to Create Services

2.6The new setFactory()
method was introduced in Symfony 2.6. Refer to older versions for the
syntax for factories prior to 2.6.

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:

Now, the method will be called statically. If the factory class 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. get) should be changed to
be non-static.

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: