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