How to Inject Values Based on Complex Expressions
The service container also supports an “expression” that allows you to inject very specific values into a service.
For example, suppose you have a service (not shown here), called App\Mail\MailerConfiguration,
which has a getMailerMethod() method on it. This returns a string - like sendmail
based on some configuration.
Suppose that you want to pass the result of this method as a constructor argument
to another service: App\Mailer. One way to do this is with an expression:
To learn more about the expression language syntax, see The Expression Syntax.
In this context, you have access to 3 functions:
serviceReturns a given service (see the example above).
parameterReturns a specific parameter value (syntax is like
service).envReturns the value of an env variable.
New in version 6.1: The env() function was introduced in Symfony 6.1.
You also have access to the Symfony\Component\DependencyInjection\Container
via a container variable. Here’s another example:
Expressions can be used in arguments, properties, as arguments with
configurator, as arguments to calls (method calls) and in
factories (service factories).
New in version 6.1: Using expressions in factories was introduced in Symfony 6.1.