2013-03-04 70 views
1

我想使用控制檯運行任務。我查了http://symfony.com/doc/2.0/components/console/introduction.htmlSymfony中的控制檯組件

它要求創建GreetCommand.php

namespace Acme\DemoBundle\Command; 

use Symfony\Component\Console\Command\Command; 
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 GreetCommand extends Command 
{ 
    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'; 
     } 

     if ($input->getOption('yell')) { 
      $text = strtoupper($text); 
     } 

     $output->writeln($text); 
    } 
} 

並創建另一個文件來運行命令,如下所示。

#!/usr/bin/env php 
# app/console 
<?php 

use Acme\DemoBundle\Command\GreetCommand; 
use Symfony\Component\Console\Application; 

$application = new Application(); 
$application->add(new GreetCommand); 
$application->run(); 

但命令來運行它像app/console demo:greet Fool

我不明白的是,爲什麼我們需要創建第二個文件?

有時候,我覺得Symfony是最難學的框架。

+0

我想這是設計以這種方式引起的FrameworkBundle Console Application命令會自動註冊從你記憶的方式中分離功能,任務等的定義。 – DonCallisto 2013-03-04 08:01:06

回答

2

在第一個文件中,您定義了您的Command類。

需要第二個文件來註冊/初始化該命令的實例。您只需告訴那裏您的應用程序將具有名爲「demo:greet」的GreetCommand(名稱在命令中定義)。

BTW當您使用全棧的Symfony2與FrameworkBundle你沒有創建第二個文件(如果我們按照Symfony2的約定)使用HttpKernel組件