Inheritance symfony2自定义控制台如何包含容器?
如何在自定义控制台命令脚本中获取容器 我希望能打电话给你Inheritance symfony2自定义控制台如何包含容器?,inheritance,symfony,console,undefined-behavior,Inheritance,Symfony,Console,Undefined Behavior,如何在自定义控制台命令脚本中获取容器 我希望能打电话给你 $this->container->get('kernel')->getCachedir(); 或 我可以在控制器中调用上述两个示例,但不能在命令中调用?。。参见下面的简化示例 namespace Portal\WeeklyConversionBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Sy
$this->container->get('kernel')->getCachedir();
或
我可以在控制器中调用上述两个示例,但不能在命令中调用?。。参见下面的简化示例
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);
}
}
返回未定义的错误消息?。。我如何定义它?我想通过添加ContainerWareCommand,我可以访问this->container?
使用
$this->getContainer()->get('kernel')->getCacheDir();
看一下文档部分的章节
来自文档,
通过使用作为命令的基类(而不是更基本的命令),您可以访问服务容器。换句话说,您可以访问任何配置的服务。谢谢。我不确定我是否想创建一个全新的服务,它似乎增加了额外的复杂性?或者我可以创建一个返回容器的服务?@Robbo_UK这只是一个例子:)这里的关键是使用$this->getContainer()而不是$this->container。然后您可以访问“内核”服务。您不需要创建任何服务,只需编辑调用容器的方式即可。(我更新了答案)
$this->getContainer()->get('kernel')->getCacheDir();