php – Symfony控制台 – 显示没有参数的命令的帮助
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了php – Symfony控制台 – 显示没有参数的命令的帮助,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1939字,纯文字阅读大概需要3分钟。
内容图文
![php – Symfony控制台 – 显示没有参数的命令的帮助](/upload/InfoBanner/zyjiaocheng/726/943f236db9e646f6b1611b0fdd8f346c.jpg)
我正在开发一个非常简单的Symfony控制台应用程序.它只有一个带有一个参数的命令,还有一些选项.
我按照this guide创建了Application类的扩展.
这是应用程序的正常用法,它工作正常:
php应用程序<参数>
这也可以正常工作(带选项的参数):
php application.php< argument> – 有些选项
如果有人在没有任何参数或选项的情况下运行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);
}
默认情况下,使用null InputInterface调用Application :: run(),所以在这里我想我可以检查参数的原始值并强制添加一个帮助选项以传递给父方法.
有没有更好的方法来实现这一目标?
解决方法:
要根据命令执行特定操作,可以使用在触发onConsoleCommand时调用的EventListener.
监听器类应该如下工作:
<?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 }
内容总结
以上是互联网集市为您收集整理的php – Symfony控制台 – 显示没有参数的命令的帮助全部内容,希望文章能够帮你解决php – Symfony控制台 – 显示没有参数的命令的帮助所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。