如何在自定义控制台命令脚本中获取容器?
我希望能够打电话
$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);
}
}
返回未定义的错误消息?..我如何定义它?我认为通过添加我可以访问的 ContainerAwareCommandthis->container?