跳到内容

如何基于复杂表达式注入值

编辑此页

服务容器也支持“表达式”,允许你将非常特定的值注入到服务中。

例如,假设你有一个服务(此处未显示),名为 App\Mail\MailerConfiguration,它有一个 getMailerMethod() 方法。这将返回一个字符串 - 比如 sendmail,基于一些配置。

假设你想将此方法的结果作为构造函数参数传递给另一个服务:App\Mailer。一种方法是使用表达式

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()"]

了解更多关于表达式语言语法

在这种上下文中,你可以访问 3 个函数

service
返回给定的服务(见上面的例子)。
parameter
返回特定的参数值(语法类似于 service)。
env
返回环境变量的值。

你还可以通过 container 变量访问 Container。 这是另一个例子

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'"]

表达式可以在 argumentsproperties 中使用,也可以作为 configurator 的参数,calls(方法调用)的参数以及 factories服务工厂)中使用。

本作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可协议获得许可。
目录
    版本