[轻量级命令行]
Command是一个很方便的命令行工具,适用于功能强大的命令行需求,但有时我们只需要类似Controller里方法那样的命令行入口,所以轻量级命令行工具Cli就提供了这样的功能。
[列出所有轻量级命令行]
在命令行执行下面:
php think cli
输出:
Available commands:helpdemo[hello]:demo:hello:hello Hellodemo:hello:hello2 Hello2
[查看某个轻量级命令行的用法]
php think cli help demo:hello:hello
输出:
HelloUsage:demo:hello:hellodemo:hello:hello testExamples:php think cli demo:hello:hello testphp think cli demo:hello:hello test2
[搜索]
假如我们搜索hello2关键字
php think cli hello2
输出:
Search Result:demo[hello]:demo:hello:hello2 Hello2
[创建轻量级命令行]
我们以创建上面列出的demo:hello:hello命令行为例
- 在
demo应用目录cli创建HelloCli.php,完整的文件路径为app/demo/cli/HelloCli.php:
<?phpnamespace app\demo\cli;use cmf\console\Cli;use think\console\Input;use think\console\Output;class HelloCli{}
- 添加
demo:hello:hello命令行
命令行名称规则:
应用名:命令行类名(小写下划线格式):方法名 如:demo:hello_test:testHello
<?phpnamespace app\demo\cli;use cmf\console\Cli;use think\console\Input;use think\console\Output;class HelloCli{/**** @param Input $input* @param Output $output* @return void*/public function hello(Input $input, Output $output){$output->writeln("<error>hello</error>");}}
此时我们列出所有命令行:
php think cli
输出:
Available commands:helpdemo[hello]:demo:hello:hello
发现demo:hello:hello已经出现在列表里了,但没有描述,如果你是PHP8.0及以上用户就可以为它添加描述、使用帮助及例子了;PHP8.0以下用户可以添加此注解不会报错,但无法实际添加描述,当然PHP7.x快结束安全维护了,升级到PHP8.0是迟早的事。
- 为
demo:hello:hello命令行添加描述
这里用到了PHP8.0新特性注解,我们创建了一个cmf\console\Cli的注解类,他有3个参数
public function __construct(string $description, array $usages = [], array $examples = [])
$description:命令行描述,字符串类型;$usages:命令行用法,数组类型子项字符串;$examples:命令行用法的实际例子,数组类型子项字符串;
现在我们就为demo:hello:hello命令行添加描述、用法和实际例子:
<?phpnamespace app\demo\cli;use cmf\console\Cli;use think\console\Input;use think\console\Output;class HelloCli{/**** @param Input $input* @param Output $output* @return void*/#[Cli('Hello',['demo:hello:hello test'],['php think cli demo:hello:hello test','php think cli demo:hello:hello test2'])]public function hello(Input $input, Output $output){$output->writeln("<error>hello</error>");}}
这样我们就完整地创建了一个轻量级命令行工具demo:hello:hello。
