Skip to content

How to Inject Values Based on Complex Expressions

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

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

The service container also supports an "expression" that allows you to inject very specific values into a service.

For example, suppose you have a third service (not shown here), called mailer_configuration, which has a getMailerMethod() method on it, which will return a string like sendmail based on some configuration. Remember that the first argument to the my_mailer service is the simple string sendmail:

1
2
3
4
5
# app/config/services.yml
services:
    app.mailer:
        class:        AppBundle\Mailer
        arguments:    [sendmail]

But instead of hardcoding this, how could we get this value from the getMailerMethod() of the new mailer_configuration service? One way is to use an expression:

1
2
3
4
5
# app/config/services.yml
services:
    my_mailer:
        class:     AppBundle\Mailer
        arguments: ["@=service('mailer_configuration').getMailerMethod()"]

To learn more about the expression language syntax, see The Expression Syntax.

In this context, you have access to 2 functions:

service
Returns a given service (see the example above).
parameter
Returns a specific parameter value (syntax is just like service).

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

1
2
3
4
services:
    my_mailer:
        class:     AppBundle\Mailer
        arguments: ["@=container.hasParameter('some_param') ? parameter('some_param') : 'default_value'"]

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

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