Symfony的控制台ContainerAwareCommand $这个 - > getContainer()产生致命错误
问题描述:
TL; DR
我创建控制台垃圾收集器,它应该能够从容器中得到服务。 这是基本的,几乎是直接从手册:
<?php
namespace SomeBundle\Console\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand,
Symfony\Component\Console\Input\InputArgument,
Symfony\Component\Console\Input\InputInterface,
Symfony\Component\Console\Input\InputOption,
Symfony\Component\Console\Output\OutputInterface;
class GarbageCollector extends ContainerAwareCommand
{
protected function configure()
{
$this
->setName('garbage:collect')
->setDescription('Collect garbage')
->addArgument(
'task',
InputArgument::REQUIRED,
'What task to execute?'
)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$task = $input->getArgument('task');
//...
$_container = $this->getContainer();
}
}
然后我试图从控制台调用它通过application.php
:
#!/usr/bin/env php
<?php
// application.php
require_once __DIR__.'/../vendor/autoload.php';
use SomeBundle\Console\Command\GarbageCollector;
use Symfony\Bundle\FrameworkBundle\Console\Application;
$application = new Application();
$application->add(new GarbageCollector);
$application->run();
将会产生致命的错误:
Argument 1 passed to Symfony\Bundle\FrameworkBundle\Console\Application::__construct() must implement interface Symfony\Component\HttpKernel\Kernel Interface, none given
手册说我唯一需要做的就是用ContainerAwareCommand
延长我的课程,但缺少一些东西。我已经写了一些废话代码传递Kernel
到Application()
:
#!/usr/bin/env php
<?php
// application.php
require_once __DIR__.'/../vendor/autoload.php';
require_once __DIR__.'/AppKernel.php';
use SomeBundle\Console\Command\GarbageCollector;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArgvInput;
$input = new ArgvInput();
$env = $input->getParameterOption(array('--env', '-e'), getenv('SYMFONY_ENV') ?: 'dev');
$debug = getenv('SYMFONY_DEBUG') !== '0' && !$input->hasParameterOption(array('--no-debug', '')) && $env !== 'prod';
$kernel = new AppKernel($env, $debug);
$application = new Application($kernel);
$application->add(new GarbageCollector);
$application->run();
和它的作品,但感觉恶心。
我需要什么使ContainerAwareCommand
实现控制台应用程序?提前致谢。
答
Symfony2通过其控制台运行程序提供了调用您的自定义命令的能力,并且它将处理注入服务容器。您只需在注册的软件包中创建您的命令,它就会自动提供给您。您在框架之外初始化您的命令,这就是为什么容器不可用于您的原因,除非您手动注入它。
您可以参考这里的食谱:
http://symfony.com/doc/current/cookbook/console/console_command.html
您可以通过运行获得所有可用的命令的列表:
php app/console
在一个侧面说明,为什么你创建垃圾收集器in/for PHP?只是好奇,因为根据我的理解,脚本执行结束后,内存将被释放。
啊,我现在可以清楚地看到:)我认为它比这更复杂。谢谢! – Nevertheless 2014-11-20 21:51:04
我需要它的网上商店,其中获取程序包括种类的构造函数。用户可以用他/她自己的图像定制产品的外观,因此,我需要在结帐前存储它们 - 如果用户添加了几张图片然后就消失了 - 我有一堆垃圾。由于$ _FILES在脚本结束后立即被转储,这些图像应该被物理地保存到临时位置,所以我需要一个定制的垃圾收集器。 – Nevertheless 2014-11-20 21:58:19
哦,好吧现在有道理:p – 2014-11-20 22:04:09