繁体   English   中英

Autowire在Symfony的依赖注入组件中不起作用

[英]Autowire not working in Symfony's Dependency Injection component

我在自定义PHP项目中使用Symfony的依赖注入组件3.4版。 我的项目在PHP 5.6上运行

"symfony/dependency-injection": "^3.4"

我已定义我的services.yaml文件以包含以下服务定义

logger:
  class: Monolog\Logger
  arguments: ["application"]
  autowire: true
  public: true

Monolog\Logger: '@logger'

plugin_context:
  class: MyProject\PluginContext
  autowire: true
  public: true

我可以确认自动加载正常,并且两个类的实例都在定义中存在,但是Logger类在PluginContext构造函数中未自动装配。 该类在以下代码中定义

use Monolog\Logger;

class PluginContext
{
    private $logger;
    function __construct(Logger $logger) {
        $this->logger = $logger;
    }
}

运行以下代码时,PHP引发异常

$container->get("plugin_context");

Catchable fatal error: Argument 1 passed to MyProject\PluginContext::__construct() must be an instance of Monolog\Logger, none given

似乎services.yaml的内容都不完整。

您的服务文件应如下所示

services:
  logger:
    class: Monolog\Logger
    arguments: ["application"]
    autowire: true
    public: true

  Monolog\Logger: '@logger'

  plugin_context:
    class: MyProject\PluginContext
    autowire: true
    public: true

更改您的FQCN $logger并使用use Psr\\Log\\LoggerInterface代替use Psr\\Log\\LoggerInterface Monolog\\Loggeruse Psr\\Log\\LoggerInterface另一件事,由于自动装配,您不需要在service.yaml指定任何内容(默认配置):

_defaults:
    autowire: true      # Automatically injects dependencies in your services.
    autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
    public: false       # Allows optimizing the container by removing unused services; this also means
                        # fetching services directly from the container via $container->get() won't work.
                        # The best practice is to be explicit about your dependencies anyway.

# makes classes in src/ available to be used as services
# this creates a service per class whose id is the fully-qualified class name
App\:
    resource: '../src/*'
    exclude: '../src/{Entity,Migrations,Tests,Kernel.php}'

Doc说:«核心捆绑包使用别名来自动绑定服务。 例如,MonologBu​​ndle创建一个ID为logger的服务。 但是它还添加了一个别名:Psr \\ Log \\ LoggerInterface,它指向记录器服务。 这就是为什么可以自动装配用Psr \\ Log \\ LoggerInterface提示的参数的原因»因此,在您的情况下,Psr \\ Log \\ LoggerInterface是Monolog的别名https://symfony.com/doc/current/service_container/autowiring.html#使用别名启用自动装配

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM