Symfony中的控制台组件

时间:2013-03-04 05:54:43

标签: symfony console

我想使用控制台运行任务。我查看了http://symfony.com/doc/2.0/components/console/introduction.html

它要求创建 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是最难学的框架。

1 个答案:

答案 0 :(得分:2)

在第一个文件中,您已经定义了Command类。

注册/初始化该命令的实例需要第二个文件。你只需告诉那里你的应用程序将使用GreetCommand名称&#34; demo:greet&#34; (在命令本身中定义的名称)。

BTW当您使用带有FrameworkBundle的全栈Symfony2时,您不必创建第二个文件(如果我们遵循Symfony2约定)因为FrameworkBundle Console Application使用HttpKernel组件自动注册Command