代码之家  ›  专栏  ›  技术社区  ›  gazareth

Symfony控制台-显示不带参数的命令帮助

  •  9
  • gazareth  · 技术社区  · 9 年前

    我正在开发一个非常简单的Symfony控制台应用程序。它只有一个带一个参数的命令和几个选项。

    我跟着 this guide 创建的扩展 Application

    这是应用程序的正常用法,它工作正常:
    php application <argument>

    这也很好(带选项的参数):
    php application.php <argument> --some-option

    如果有人跑步 php application.php 没有任何参数或选项,我希望它像用户运行一样运行 php application.php --help .

    我确实有一个可行的解决方案,但它不是最佳的,可能有点脆弱。在我的扩展 应用 类,我重写了 run() 方法如下:

    /**
     * Override parent method so that --help options is used when app is called with no arguments or options
     *
     * @param InputInterface|null $input
     * @param OutputInterface|null $output
     * @return int
     * @throws \Exception
     */
    public function run(InputInterface $input = null, OutputInterface $output = null)
    {
        if ($input === null) {
            if (count($_SERVER["argv"]) <= 1) {
                $args = array_merge($_SERVER["argv"], ["--help"]);
                $input = new ArgvInput($args);
            }
        }
        return parent::run($input, $output);
    }
    

    默认情况下, Application::run() 使用null调用 InputInterface ,所以在这里我想我可以检查参数的原始值,并强制添加一个帮助选项来传递给父方法。

    有没有更好的方法来实现这一点?

    2 回复  |  直到 9 年前
        1
  •  11
  •   gazareth    9 年前

    我设法找到了一个解决方案,不涉及触碰 Application 根本不上课。要从另一个命令中调用帮助命令,请执行以下操作:

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int
     * @throws \Symfony\Component\Console\Exception\ExceptionInterface
     */
    protected function outputHelp(InputInterface $input, OutputInterface $output)
    {
        $help = new HelpCommand();
        $help->setCommand($this);
        return $help->run($input, $output);
    }
    
        2
  •  3
  •   chalasr    9 年前

    要根据命令执行特定操作,可以使用 EventListener onConsoleCommand 被激发。

    侦听器类的工作方式如下:

    <?php
    
    namespace AppBundle\EventListener;
    
    use Symfony\Component\Console\Event\ConsoleCommandEvent;
    use Symfony\Component\Console\Command\HelpCommand;
    
    class ConsoleEventListener
    {
        public function onConsoleCommand(ConsoleCommandEvent $event)
        {
            $application = $event->getCommand()->getApplication();
            $inputDefinition = $application->getDefinition();
    
            if ($inputDefinition->getArgumentCount() < 2) {
                $help = new HelpCommand();
                $help->setCommand($event->getCommand());
    
                return $help->run($event->getInput(), $event->getOutput());
            }
        }
    }
    

    服务声明:

    services:
         # ...
         app.console_event_listener:
             class: AppBundle\EventListener\ConsoleEventListener
             tags:
                 - { name: kernel.event_listener, event: console.command, method: onConsoleCommand }