Skip to content

How to Inject Values Based on Complex Expressions

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

Read the updated version of this page for Symfony 7.2 (the current stable version).

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:

1
2
3
4
5
6
7
8
9
10
11
# config/services.yaml
services:
    # ...

    App\Mail\MailerConfiguration: ~

    App\Mailer:
        # the '@=' prefix is required when using expressions for arguments in YAML files
        arguments: ['@=service("App\\Mail\\MailerConfiguration").getMailerMethod()']
        # when using double-quoted strings, the backslash needs to be escaped twice (see https://yaml.org/spec/1.2/spec.html#id2787109)
        # arguments: ["@=service('App\\\\Mail\\\\MailerConfiguration').getMailerMethod()"]

Learn more about the expression language syntax.

In this context, you have access to 3 functions:

service
Returns a given service (see the example above).
parameter
Returns a specific parameter value (syntax is like service).
env
Returns the value of an env variable.

6.1

The env() function was introduced in Symfony 6.1.

You also have access to the Container via a container variable. Here's another example:

1
2
3
4
5
# config/services.yaml
services:
    App\Mailer:
        # the '@=' prefix is required when using expressions for arguments in YAML files
        arguments: ["@=container.hasParameter('some_param') ? parameter('some_param') : 'default_value'"]

Expressions can be used in arguments, properties, as arguments with configurator, as arguments to calls (method calls) and in factories (service factories).

6.1

Using expressions in factories was introduced in Symfony 6.1.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version