如何使用autowire命令设置控制台应用程序?
问题描述:
请帮我配置控制台应用程序,在第一 - 配置如何使用autowire命令设置控制台应用程序?
#!/usr/bin/env php
<?php
use ....
...
$container = new ContainerBuilder();
$config = new YamlFileLoader($container, new FileLocator(__DIR__));
$config->load('config.yml');
$output = $container->get('symfony.console_output');$logger = $container->get('logger');
//I want automatic injection!!!!
$helloCommand = new HelloCommand($container, $logger);
$application = $container->get('symfony.application');
$application->add($helloCommand);
$application->run(null, $output);
而且我config.yml
services:
logger:
class: Symfony\Component\Console\Logger\ConsoleLogger
arguments:
- '@symfony.console_output'
symfony.application:
class: Symfony\Component\Console\Application
calls:
//by this variant autowire not working
- [add, [ '@app.command.hello_command' ]]
- [setDispatcher, ['@symfony.event_dispatcher']]
...
app.command.hello_command:
class: App\Command\HelloCommand
autowire: true
tags:
- { name: console.command }
所以我HelloCommand具有构造与ContainerInterface和LoggerInterface且仅当我设置它的工作直接参数,其他我有关于错误的构造函数的错误
或者可能存在另一种配置方式config.yml 只有记录器 - 它将通过设置['@logger' ]作为参数,但我怎样才能设置当前容器作为参数? 还是我心底必须安装完整的symfony与httpkernel(但并不需要)
HelloCommand http://pastebin.com/VRr3FM7Q
你如何配置决定
app.command.hello_command:
class: App\Command\HelloCommand
arguments:
- '@service_container'
- '@logger'
tags:
- { name: console.command }
答
问题在于你的命令:
app.command.hello_command:
class: App\Command\HelloCommand
autowire: true
tags:
- { name: console.command }
这会错过所需的2个构造函数参数:$container
,$logger
并且可能是您为什么会得到异常。你可以像这样添加构造参数:
app.command.hello_command:
class: App\Command\HelloCommand
arguments:
- '@service_container'
- '@logger'
[...]
我不确定service_container的id是否正确。我从来没有通过容器或ContainerAware的东西,但你得到的总体思路。 ;)
如果您已经尝试将其注册为服务,为什么您需要手动创建'HelloCommand'对象?还请显示你的'HelloCommand'类的代码。 – xabbuh
它的替代变体;为了说明,如果我创建如果手动与初始化 - 一切正常,但与配置注入不起作用 – Lenny
HelloCommand http://pastebin.com/VRr3FM7Q – Lenny