gaz*_*eth 4 php symfony symfony-console
我正在开发一个非常简单的Symfony控制台应用程序。它只有一个带有一个参数的命令,以及几个选项。
我按照本指南创建了Application
该类的扩展。
这是该应用程序的正常用法,并且工作正常:
php application <argument>
这也很好用(带有选项的参数):
php application.php <argument> --some-option
如果有人在运行时php application.php
没有任何参数或选项,那么我希望它像用户在运行一样运行php application.php --help
。
我确实有一个可行的解决方案,但它不是最佳解决方案,可能有点脆弱。在扩展Application
类中,我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);
}
Run Code Online (Sandbox Code Playgroud)
默认情况下,Application::run()
它以null调用InputInterface
,因此在这里,我认为可以检查参数的原始值并强行添加一个帮助选项以传递给父方法。
有没有更好的方法来实现这一目标?
我设法提出了一个完全不涉及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);
}
Run Code Online (Sandbox Code Playgroud)
要根据命令执行特定操作,您可以使用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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
服务声明:
services:
# ...
app.console_event_listener:
class: AppBundle\EventListener\ConsoleEventListener
tags:
- { name: kernel.event_listener, event: console.command, method: onConsoleCommand }
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1027 次 |
最近记录: |