0
如何获取自定义控制台命令脚本中的容器?symfony2自定义控制台如何包含容器?
IM希望能够调用
$this->container->get('kernel')->getCachedir();
或
$this->getDoctrine();
我可以调用该命令中的控制器内,但不是上面的两个例子?..见下文
简化示例namespace Portal\WeeklyConversionBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class ExampleCommand extends ContainerAwareCommand
{
protected function configure()
{
$this->setName('demo:greet')
->setDescription('Greet someone')
->addArgument('name', InputArgument::OPTIONAL, 'Who do you want to greet?')
->addOption('yell', null, InputOption::VALUE_NONE, 'If set, the task will yell in uppercase letters')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$name = $input->getArgument('name');
if ($name) {
$text = 'Hello '.$name;
} else {
$text = 'Hello';
}
// this returns an error?
// $cacheDir = $this->container->get('kernel')->getCachedir();
// edit - this works
$this->getContainer()->get('kernel')->getCacheDir();
$output->writeln($text);
}
}
返回一个未定义的错误信息?..我如何定义它?我认为,通过增加ContainerAwareCommand,我将有机会获得this->container?
感谢您的支持。林不知道我想创建一个全新的服务,似乎它增加了额外的完整性?或者我可以创建一个返回容器的服务? – 2013-03-06 17:03:45
@Robbo_UK这只是一个例子:)这里的关键是使用$ this-> getContainer()而不是$ this-> container。然后你可以访问'内核'服务。 您不需要创建任何服务,只需编辑您调用容器的方式即可。 (我更新了答案) – 2013-03-06 17:06:28
它工作。谢谢 :-) – 2013-03-06 17:10:51