首页 > 解决方案 > 清理控制台命令帮助输出

问题描述

我的应用程序中有很多用于维护任务的 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, --verboseflags 等。到目前为止,我一直无法找到任何优雅的(laravel)方式来做到这一点。有什么建议么?

标签: phplaravel

解决方案


打开app\Console\Kernel.phplaravel 安装标配的文件。它延伸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}(选项在命令定义中以开头--,参数不是)。


推荐阅读