忽略二传手注射中缺少的方法

我正在使用PHP特性作为mixin注入可选服务,即

<?php

trait Logger
{
    private LoggerInterface $logger;

    public function getLogger(): LoggerInterface
    {
        return $this->logger;
    }

    /**
     * Inject logger instance (called by the DI container)
     */
    public function setLogger(LoggerInterface $logger): self
    {
        $this->logger = $logger;

        return $this;
    }
}

然后在课堂上使用这个特征:

class UserService
{
    use Logger;
    /* ... */
}

Because this trait can be used in any class, I create a method injection call for all classes in App\ namespace to inject the logger:

App\:
    # ...
    calls:
        - [setLogger, ['@monolog.logger']]

However, when Symfony encounters a service that doesn't implement setLogger method, it throws an error saying 'Invalid service: method "setLogger()" does not exist.'

由于这种注入应该是可选的,如果该方法不存在,是否有办法告诉Symfony忽略该调用?

评论
  • 最后的最后
    最后的最后 回复

    您正在用这个重新发明轮子。

    Symfony开箱即用提供此功能。

    If a service implements LoggerAwareInterface (link), Symfony will automatically call setLogger() on the service to inject the logger service.

    And since the same package also includes a LoggerAwareTrait, (link) you can simply do the following:

    class FooService implements LoggerAwareInterface
    {
        use LoggerAwareTrait;
    }
    

    And that's it. If you are using the default autowire/autoconfigure settings, no other configuration needed, and the logger will be automatically injected.

    You can implement the above, remove your calls: setLoggerfrom services.yaml, and the logger will be injected in the classes you want, are won't in the classes you don't.