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
实现控制台应用程序?提前致谢。
啊,我现在可以清楚地看到:)我认为它比这更复杂。谢谢! – Nevertheless 2014-11-20 21:51:04
我需要它的网上商店,其中获取程序包括种类的构造函数。用户可以用他/她自己的图像定制产品的外观,因此,我需要在结帐前存储它们 - 如果用户添加了几张图片然后就消失了 - 我有一堆垃圾。由于$ _FILES在脚本结束后立即被转储,这些图像应该被物理地保存到临时位置,所以我需要一个定制的垃圾收集器。 – Nevertheless 2014-11-20 21:58:19
哦,好吧现在有道理:p – 2014-11-20 22:04:09