yii控制台命令自定义帮助信息

ajsxfq5m  于 2023-11-19  发布在  其他
关注(0)|答案(2)|浏览(212)

我在yii驱动的项目中创建了commands/TestCommand.php文件:

class TestCommand extends CConsoleCommand
{
    public function actionIndex()
    {
        echo "Hello World!\n";
    }
}

字符串
它通过yiic变得可见:

Yii command runner (based on Yii v1.1.14)
Usage: yiic.php <command-name> [parameters...]

The following commands are available:
 - message
 - migrate
 - shell
 - test     <<<
 - webapp

To see individual command help, use the following:
   yiic.php help <command-name>


如果我试图获取有关此控制台命令的帮助信息:

php yiic.php help test


我看到默认文本:

Usage: yiic.php test index


我如何编写我的TestCommand类来显示我的帮助信息?它是一些公共字段还是返回帮助文本的特殊方法?我需要这样的东西:

php yiic.php help webapp


我需要的结果:

USAGE
  yiic webapp <app-path> [<vcs>]

DESCRIPTION
  This command generates an Yii Web Application at the specified location.

PARAMETERS
 * app-path: required, the directory where the new application will be created.
   If the directory does not exist, it will be created. After the application
   is created, please make sure the directory can be accessed by Web users.
 * vcs: optional, version control system you're going to use in the new project.
   Application generator will create all needed files to the specified VCS
   (such as .gitignore, .gitkeep, etc.). Possible values: git, hg. Do not
   use this argument if you're going to create VCS files yourself.

wbgh16ku

wbgh16ku1#

您可以重写默认的getHelp方法来实现帮助!
它必须返回作为帮助文本的字符串。
提供命令说明。可以重写此方法以返回实际的命令说明。
以下是默认方法:

public function getHelp()
{
    $help='Usage: '.$this->getCommandRunner()->getScriptName().' '.$this->getName();
    $options=$this->getOptionHelp();
    if(empty($options))
        return $help."\n";
    if(count($options)===1)
        return $help.' '.$options[0]."\n";
    $help.=" <action>\nActions:\n";
    foreach($options as $option)
        $help.='    '.$option."\n";
    return $help;
}

字符串
您还可以覆盖在getHelp中调用的默认getOptionHelp方法
提供命令选项帮助信息。默认实现将返回所有可用的操作及其相应的选项信息。

dgjrabp2

dgjrabp22#

更简单的解决方案是使用文档注解。
例如,对于选项

/**
     * @var bool whether to enable ANSI color in the output.
     * If not set, ANSI color will only be enabled for terminals that support it.
     */
    public $color;

字符串
或命令本身

/**
     * Flushes given cache components.
     *
     * For example,
     *
     * ```
     * # flushes caches specified by their id: "first", "second", "third"
     * yii cache/flush first second third
     * ```
     */
    public function actionFlush()


如果您查看默认操作,您应该会看到它是如何工作的,并能够模拟它。

相关问题