1

コンソールを使用してタスクを実行したい。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

私が理解できないのは、なぜ2番目のファイルを作成する必要があるのか​​ということです。

時々、Symfonyは学ぶのが最も難しいフレームワークだと感じます。

4

1 に答える 1

2

最初のファイルで Command クラスを定義しました。

そのコマンドのインスタンスを登録/初期化するには、2 番目のファイルが必要です。アプリケーションに「demo:greet」という名前の GreetCommand (コマンド自体で定義された名前) があることを伝えるだけです。

ところで、FrameworkBundle でフルスタックの Symfony2 を使用する場合、2 番目のファイルを作成する必要はありません (Symfony2 の規則に従っていれば) コマンドは、HttpKernel コンポーネントを使用してFrameworkBundle コンソール アプリケーションによって自動的に登録されます。

于 2013-03-04T08:15:06.797 に答える