我在我的自定义PHP项目中使用Symfony的依赖注入组件3.4版。我的项目在PHP5.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发布于 2018-04-03 16:55:13
改变你的FQCN $logger,用这个use Psr\Log\LoggerInterface代替Monolog\Logger另一个东西,多亏了自动装配,你不需要在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说:“核心捆绑包使用别名来允许服务自动连接。例如,MonologBundle创建了一个id为logger的服务。但它还添加了一个指向记录器服务的别名: Psr\Log\LoggerInterface。这就是使用Psr\Log\LoggerInterface类型提示的参数可以自动连接的原因。因此,在您的示例中,Psr\Log\LoggerInterface是Monolog https://symfony.com/doc/current/service_container/autowiring.html#using-aliases-to-enable-autowiring的别名
发布于 2018-04-03 16:10:43
看起来services.yaml的内容都不是很满。
您的服务文件应如下所示
services:
logger:
class: Monolog\Logger
arguments: ["application"]
autowire: true
public: true
Monolog\Logger: '@logger'
plugin_context:
class: MyProject\PluginContext
autowire: true
public: truehttps://stackoverflow.com/questions/49624474
复制相似问题