php - 清理控制台命令帮助输出
问题描述
我的应用程序中有很多用于维护任务的 laravel 控制台命令,在绝大多数情况下,我的用例需要和支持的帮助对话框提供的默认选项很少。典型的帮助输出如下所示:
Description:
Do stuff
Usage:
myapp:mycommand
Options:
-h, --help Display this help message
-q, --quiet Do not output any message
-V, --version Display this application version
--ansi Force ANSI output
--no-ansi Disable ANSI output
-n, --no-interaction Do not ask any interactive question
--env[=ENV] The environment the command should run under
-v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
我不喜欢向用户提供我无意支持的选项的想法,因此我想从--help
文本中省略这些选项以清理显示的信息。例如--no-interaction
, --no-ansi
, --ansi
, --verbose
flags 等。到目前为止,我一直无法找到任何优雅的(laravel)方式来做到这一点。有什么建议么?
解决方案
打开app\Console\Kernel.php
laravel 安装标配的文件。它延伸Illuminate\Foundation\Console\Kernel
.
现在,您可以使用以下代码覆盖构造函数:
// Define a property where the keys are the command name, and the values
// are arrays with the options that you are allowed to pass.
protected $optionFilters = [
'my-command-name' => [
'user',
'raw',
]
];
public function __construct(Application $app, Dispatcher $events)
{
parent::__construct($app, $events);
$commands = $this->getArtisan()->all();
foreach ($commands as $command) {
// Now we simply loop all registered commands, and see if we should
// apply a filter.
if ($filter = array_get($this->optionFilters, $command->getName())) {
$options = array_filter(
$command->getDefinition()->getOptions(),
function (\Symfony\Component\Console\Input\InputOption$option) use ($filter) {
return in_array($option->getName(), $filter);
});
// Set the new options to the command.
$command->getDefinition()->setOptions($options);
}
}
}
现在,如果您之前定义了如下命令:
protected $signature = 'my-command-name {--user} {--raw} {--type}';
运行上面的循环会{--type}
从命令中省略。
虽然从 Laravel 自己的工匠命令中删除选项时,我确实注意到了一些副作用(比如php artisan help
当我删除选项时抛出一些错误的命令--format
)。所以你必须检查一些。
还有一个
getArguments()
andsetArguments()
可以用来省略像{user?}
or之类的参数{user=foo}
(选项在命令定义中以开头--
,参数不是)。
推荐阅读
- c# - 如何在 C# 中对具有抽象内部类型的泛型进行模式匹配?
- python - Pandas 中 Excel SUM 的替代方案
- sql - 在存储过程 Round() 函数中将 varchar(255) 转换为浮点数?
- html - 打开垫子扩展面板正在移动对面的柱子,如何保持静止?
- jquery - 我的 Woocommerce 网站上出现 Jquery 错误
- mysql - MYSQL 创建“复杂”视图
- r - 通过 FlexTable 列表应用条件文本修改
- pyspark - 如何以将“日期”分组到不同列而不是将所有内容组合在同一列中的方式进行联合
- javascript - 搜索 API 上的重新渲染过多
- powerbi - 如何区分 PowerBI Measure 中的 BLANK 和 0?