New in Symfony 6.1: Expressions as Service Factories
May 10, 2022 • Published by Javier Eguiluz
Symfony 6.1 is backed by:
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
The service container provided by the DependencyInjection component allows you to configure the creation of objects. However, sometimes you need to apply the factory design pattern to delegate the object creation to some special object called "the factory".
In Symfony 6.1 we're improving the service container to allow you to use expressions as service factories. This can help you in advanced cases such as selecting the factory based on the value of an environment variable.
The syntax to use depends on the configuration format:
- in YAML:
factory: '@=service("foo").bar()'
- in XML:
<factory expression="service('foo').bar()" />
- in PHP:
->factory(expr('service("foo").bar()'))
The following example shows how to select the factory to use based on the value of a configuration parameter:
1 2 3 4 5 6
# config/services.yaml
services:
App\Mailer:
factory: "@=parameter('some_param') ? service('some_service') : arg(0)"
arguments:
- '@some_other_service'
The arg()
function returns the value of arguments passed to the factory (e.g.
arg(0)
returns the first argument, arg(1)
returns the second argument, etc.)
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.