如何在自定义控制台命令脚本中获取容器?
我希望能够致电
$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?
答案 0 :(得分:2)
如何使用,
$this->getContainer()->get('kernel')->getCacheDir();
请查看文档Getting Services from the Service Container部分的How to create a Console Command部分。
来自文档,
通过使用ContainerAwareCommand作为命令的基类(而不是更基本的命令),您可以访问服务容器。换句话说,您可以访问任何已配置的服务。