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.

たとえば、getMailerMethod() メソッドを持つ App\Mail\MailerConfiguration というサービス (ここには表示されていません) があるとします。これは文字列を返します - sendmail のように、いくつかの設定に基づいています。

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:

このメソッドの結果をコンストラクタ引数として別のサービス App\Mailer に渡したいとします。これを行う 1 つの方法は、式を使用することです。
  • YAML
    YAML
  • XML
    XML
  • PHP
    PHP
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()"]

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

式言語の構文の詳細については、式の構文を参照してください。

In this context, you have access to 3 functions:

このコンテキストでは、次の 3 つの機能にアクセスできます。
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

6.1

The env() function was introduced in Symfony 6.1.

env() 関数は Symfony 6.1 で導入されました。

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

コンテナ変数を介してコンテナにアクセスすることもできます。別の例を次に示します。
  • YAML
    YAML
  • XML
    XML
  • PHP
    PHP
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).

式は、引数、プロパティ、configurator の引数、呼び出し (メソッド呼び出し) および infactory (サービス ファクトリ) への引数として使用できます。

6.1

6.1

Using expressions in factories was introduced in Symfony 6.1.

ファクトリでの式の使用は、Symfony 6.1 で導入されました。