Skip to content

v3 upgrade to v4

Inhere edited this page Oct 18, 2021 · 8 revisions

v3升级到v4

推荐升级到 v4 版本,v4使用上更加简单易用

大部分都是兼容的,唯有选项参数的解析、绑定变动较大。之前获取输入参数、选项都是通过 Input 对象,v4 重构了选项参数的解析。

升级改动说明:

  • PHP 版本需要 7.3+
  • 将原来的 $input->getXXXOpt() 替换为 $fs->getOpt()
  • 将原来的 $input->getXXXArg() 替换为 $fs->getArg()
  • 方法上的@options @arguments注释内容会被严格解析,因此名称和后面的规则至少需要间隔两个空格

v4示例 - 通过注释绑定选项参数:

    /**
     * show next execution datetime for an cron expression.
     *
     * @arguments
     *  expression      string;The cronTab expression. eg: `20 10 * * *`;required
     *
     * @options
     *  -n, --next      int;Show next number exec datetime. default number is 3.
     *  -p, --prev      bool;Show previsions exec datetime
     *
     * @param FlagsParser $fs
     * @param Output $output
     *
     * @throws Exception
     */
    public function someCommand(FlagsParser $fs, Output $output): void
    {
        $expr = $fs->getArg('expression'); // will get string value
        $prev = $fs->getOpt('prev'); // will get bool value

        $nextNum  = $fs->getOpt('next', 3); // will get int value

        $output->colored('Cron Expression: ' . $expr);
    }

v4示例 - 通过 FlagsParsr 对象绑定选项参数:

    /**
     * Configure for the subcommand `some`
     */
    protected function someConfigure(): void
    {
        // 在独立命令里
        // $fs = $this->getFlags();
        // 在group的子命令里
        $fs = $this->getActionFlags();

        $fs->addArg('topic', 'The language/topic for search. eg: go, php, java, lua, python, js ...');
        $fs->addArg('question', 'The question search.');

        $fs->addOpt('search', 's', 'search by the keywords');
        // $fs->addOpt('T', 't', 'query');

        $fs->setMoreHelp(<<<HELP
<b>Special pages</b>
There are several special pages that are not cheat sheets. Their names start with colon and have special meaning.

.... ...
HELP
        );
        $fs->setExampleHelp([
            '{fullCmd} go reverse list'
        ]);
    }