Skip to content

v4 create command

Inhere edited this page May 28, 2022 · 9 revisions

创建独立命令

代码示例

使用之前的代码示例,来自我的项目 inhere/kite

<?php declare(strict_types=1);

namespace Inhere\Kite\Console\Command;

use Inhere\Console\Command;
use Inhere\Console\IO\Input;
use Inhere\Console\IO\Output;
use Inhere\Kite\Component\CliMarkdown;
use Toolkit\Cli\Color;
use function file_get_contents;

/**
 * Class MarkdownCommand
 */
class MarkdownCommand extends Command
{
    /** @var string  */
    protected static $name = 'markdown';

    /**
     * @var string
     */
    protected static $description = 'render markdown file on terminal';

    /**
     * @return string[]
     */
    public static function aliases(): array
    {
        return ['md', 'mkdown'];
    }

    /**
     * @arguments
     *   mdfile     string;The markdown file path;required
     *
     * @param  Input $input
     * @param  Output $output
     */
    protected function execute(Input $input, Output $output)
    {
        $filename = $this->flags->getArg('mdfile');

        $text = file_get_contents($filename);

        // parse content
        $md  = new CliMarkdown();
        $doc = $md->parse($text);
        $doc = Color::parseTag(rtrim($doc));

        // $output->colored("Document for the #$nameString");
        $output->writeRaw($doc);
    }
}

TIP: 创建好命令后需要注册到Application, 请继续看 注册命令 章节

绑定选项参数

命令可以通过方法注释快速绑定命令选项和参数,运行时console会自动解析并绑定到当前命令

  • @arguments 后面的即是命令参数
  • @options 后面的即是命令选项
    • 注意选项名和后面的设置描述需间隔一定距离
    • 规则以分号 ; 分割每个部分 (完整规则:type;desc;required;default;shorts)
    • 默认是 string 类型,可以忽略

选项参数解析使用的 php-toolkit/pflag 更多说明可以点击查看

绑定子命令

v4 版本之后,独立命令也可以通过 subCommands 绑定子级命令,并且支持多个层级。可以实现类似于 git remote add 这样的多层级命令

代码示例来自 inhere/kite...ToolCommand.php

    protected function subCommands(): array
    {
        return [
            OpenCmd::class,
            LnCommand::class,
        ];
    }