在Symfony控制台中使用全局选项

时间:2015-09-28 18:07:50

标签: php symfony

我正在编写控制台应用程序,需要允许用户在不同的环境之间切换。

<?php
$console = new Symfony\Component\Console\Application;
$dispatcher = new EventDispatcher();
$console->setDispatcher($dispatcher);

$console->getDefinition()->addOptions([
    new InputOption(
        '--env',
        '-e',
        InputOption::VALUE_OPTIONAL,
        'The environment to operate in.',
        'DEV'
    )
]);

$dispatcher->addListener(ConsoleEvents::COMMAND, function (ConsoleCommandEvent $event) {
    // get the input instance
    $input = $event->getInput();

    print_R($event->getInput()->getOption('env'));exit;
});

$console->run();

运行命令(cmdname --env=test)时,我希望看到test。但是,我收到错误消息The "env" option does not exist.

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

我认为InputOption类构造函数不需要破折号:

$console->getDefinition()->addOptions([
    new InputOption(
        'env',
        'e',
        InputOption::VALUE_OPTIONAL,
        'The environment to operate in.',
        'DEV'
    )
]);

请参阅http://symfony.com/doc/current/components/console/console_arguments.html

答案 1 :(得分:-1)

创建了一个小的&#34; var_dump测试用例&#34;。以前从未与symfony / console取得联系,但似乎没有通过ConsoleCommandEvent中的输入接口解析选项或参数。

将您的代码用于&#34;常规&#34;命令,而不是在侦听器内部,你的环境设置正确。

#!/usr/bin/env php
<?php
require_once('vendor/autoload.php');

use Symfony\Component\Console\Application;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;

$console = new Application();

$dispatcher = new EventDispatcher();
$console->setDispatcher($dispatcher);

$console->getDefinition()->addOptions([
    new InputOption(
        '--env',
        '-e',
        InputOption::VALUE_OPTIONAL,
        'The environment to operate in.',
        'DEV'
    )
]);

$console
    ->register('envtest')
    ->setCode(function (InputInterface $input,OutputInterface $output) {
//      $output->writeln('What is my env?')
        var_dump($input->getOptions());
    });

$dispatcher->addListener(ConsoleEvents::COMMAND, function (ConsoleCommandEvent $event) {

    $command = $event->getCommand();
    $application = $command->getApplication();

    //Check if your option is registerd within the console application
    var_dump($application->getDefinition()->getOptions());

    $input = $event->getInput();
    var_dump($input->getOptions());

    // get the input instance
    //var_dump($event->getInput()->getOptions());

});


$console->run();