将注入对象作为服务的参数

时间:2019-07-02 10:22:33

标签: php symfony dependency-injection

我正尝试使用依赖项注入为Logger服务动态地提供解析类的名称(或解析类实例本身),如下面的代码所示。使用Symfony DI甚至可以做到这一点,我找不到解决方案。

提前谢谢!

services.yml

services:
    // ...
    MyLogger\Logger:
        arguments: ["%className%"] // is it possible to do sth. like this?

Logger.php

class Logger
{
    public function __construct(string $className)
    {
        $this->className = $className;
    }

    public function log(string $message)
    {
        echo "{$this->className}: {$message}";
    }
}

MyClass.php

use MyLogger\Logger;

class MyClass
{
    public function __construct(Logger $logger)
    {
        $this->logger = $logger;
    }

    public function getFoo()
    {
        // Should echo: "MyClass: Called getFoo()"
        $this->logger->log("Called getFoo()");
    }
}

0 个答案:

没有答案