Symfony config.yml - 如何按名称传递构造函数参数?

Symfony config.yml - How to pass constructor arguments by name?

我正尝试在我的 Symfony WebApp 中为使用 Monlog 创建的日志条目使用自定义格式化程序:

//config.yml
services:
    monolog.formatter.extended:
        class: Monolog\Formatter\LineFormatter
        arguments:
            format: "[%%datetime%%] %%channel%%.%%level_name%% ...\n\n"
            allowInlineLineBreaks: true
            ignoreEmptyContextAndExtra: true
        calls:
            - [includeStacktraces]

使用此格式化程序创建的所有日志条目都以 [1]... 开头,而不是像 [2015-12-16 10:40:23]...

那样插入正确的时间戳

当我删除两个附加参数 allowInlineLineBreaksignoreEmptyContextAndExtra 时,这个问题没有出现:

arguments:
    format: "[%%datetime%%] %%channel%%.%%level_name%% ...\n\n"

然而,当我不按名称传递参数而只是作为完整列表传递时,一切正常。 LineFormatter 构造函数如下所示:

public function __construct($format = null, $dateFormat = null, $allowInlineLineBreaks = false, $ignoreEmptyContextAndExtra = false) { ...}

因此将参数添加为列表工作正常:

 arguments:
    - "[%%datetime%%] %%channel%%.%%level_name%% ...\n\n"
    - null
    - true
    - true

按名称传递参数有什么问题?我已经在几个示例中看到了这一点,但很明显我使用它的方式有问题?

老实说,我从未见过使用键注入参数。 我知道您可以在处理参数或使用 setter 注入时使用键,如文档所述: http://symfony.com/doc/current/book/service_container.html#optional-dependencies-setter-injection

如果你想使用 setter 注入,你可以这样做:

//config.yml
services:
    some.service.name:
        class: SomeClass
        calls:
            - [setFormat, "[%%datetime%%] %%channel%%.%%level_name%%"]

但是 Monolog LineFormatter 不支持。

最后我想你会选择普通数组模式。

我希望这对您有所帮助,如果您有一些文档显示使用键的示例,我希望看到它,然后我们可以讨论它!