2014-11-20 52 views
2

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延長我的課程,但缺少一些東西。我已經寫了一些廢話代碼傳遞KernelApplication()

#!/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實現控制檯應用程序?提前致謝。

回答

3

Symfony2通過其控制檯運行程序提供了調用您的自定義命令的能力,並且它將處理注入服務容器。您只需在註冊的軟件包中創建您的命令,它就會自動提供給您。您在框架之外初始化您的命令,這就是爲什麼容器不可用於您的原因,除非您手動注入它。

您可以參考這裏的食譜:

http://symfony.com/doc/current/cookbook/console/console_command.html

您可以通過運行獲得所有可用的命令的列表:

php app/console 

在一個側面說明,爲什麼你創建垃圾收集器in/for PHP?只是好奇,因爲根據我的理解,腳本執行結束後,內存將被釋放。

+0

啊,我現在可以清楚地看到:)我認爲它比這更復雜。謝謝! – Nevertheless 2014-11-20 21:51:04

+0

我需要它的網上商店,其中獲取程序包括種類的構造函數。用戶可以用他/她自己的圖像定製產品的外觀,因此,我需要在結帳前存儲它們 - 如果用戶添加了幾張圖片然後就消失了 - 我有一堆垃圾。由於$ _FILES在腳本結束後立即被轉儲,這些圖像應該被物理地保存到臨時位置,所以我需要一個定製的垃圾收集器。 – Nevertheless 2014-11-20 21:58:19

+0

哦,好吧現在有道理:p – 2014-11-20 22:04:09

相關問題