-
Notifications
You must be signed in to change notification settings - Fork 48
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
这样的多层级命令
protected function subCommands(): array
{
return [
OpenCmd::class,
LnCommand::class,
];
}
我的其他PHP项目
- inhere/kite 方便本地开发和使用的个人CLI工具应用
- php-toolkit/pflag PHP编写的,通用的命令行标志(选项和参数)解析库
- phppkg/easytpl 使用简单且快速的 PHP 模板引擎
- inhere/php-validate 一个简洁小巧且功能完善的php验证库
- inhere/sroute 轻量且快速的HTTP请求路由库