[轻量级命令行]

Command是一个很方便的命令行工具,适用于功能强大的命令行需求,但有时我们只需要类似Controller里方法那样的命令行入口,所以轻量级命令行工具Cli就提供了这样的功能。

[列出所有轻量级命令行]

在命令行执行下面:

  1. php think cli

输出:

  1. Available commands:
  2. help
  3. demo[hello]:
  4. demo:hello:hello Hello
  5. demo:hello:hello2 Hello2

[查看某个轻量级命令行的用法]

  1. php think cli help demo:hello:hello

输出:

  1. Hello
  2. Usage:
  3. demo:hello:hello
  4. demo:hello:hello test
  5. Examples:
  6. php think cli demo:hello:hello test
  7. php think cli demo:hello:hello test2

[搜索]

假如我们搜索hello2关键字

  1. php think cli hello2

输出:

  1. Search Result:
  2. demo[hello]:
  3. demo:hello:hello2 Hello2

[创建轻量级命令行]

我们以创建上面列出的demo:hello:hello命令行为例

  1. demo应用目录cli创建HelloCli.php,完整的文件路径为app/demo/cli/HelloCli.php
  1. <?php
  2. namespace app\demo\cli;
  3. use cmf\console\Cli;
  4. use think\console\Input;
  5. use think\console\Output;
  6. class HelloCli
  7. {
  8. }
  1. 添加demo:hello:hello命令行

命令行名称规则:

应用名:命令行类名(小写下划线格式):方法名 如:demo:hello_test:testHello

  1. <?php
  2. namespace app\demo\cli;
  3. use cmf\console\Cli;
  4. use think\console\Input;
  5. use think\console\Output;
  6. class HelloCli
  7. {
  8. /**
  9. *
  10. * @param Input $input
  11. * @param Output $output
  12. * @return void
  13. */
  14. public function hello(Input $input, Output $output)
  15. {
  16. $output->writeln("<error>hello</error>");
  17. }
  18. }

此时我们列出所有命令行:

  1. php think cli

输出:

  1. Available commands:
  2. help
  3. demo[hello]:
  4. demo:hello:hello

发现demo:hello:hello已经出现在列表里了,但没有描述,如果你是PHP8.0及以上用户就可以为它添加描述、使用帮助及例子了;PHP8.0以下用户可以添加此注解不会报错,但无法实际添加描述,当然PHP7.x快结束安全维护了,升级到PHP8.0是迟早的事。

  1. demo:hello:hello命令行添加描述

这里用到了PHP8.0新特性注解,我们创建了一个cmf\console\Cli的注解类,他有3个参数

  1. public function __construct(string $description, array $usages = [], array $examples = [])

$description:命令行描述,字符串类型;
$usages:命令行用法,数组类型子项字符串;
$examples:命令行用法的实际例子,数组类型子项字符串;

现在我们就为demo:hello:hello命令行添加描述、用法和实际例子:

  1. <?php
  2. namespace app\demo\cli;
  3. use cmf\console\Cli;
  4. use think\console\Input;
  5. use think\console\Output;
  6. class HelloCli
  7. {
  8. /**
  9. *
  10. * @param Input $input
  11. * @param Output $output
  12. * @return void
  13. */
  14. #[Cli(
  15. 'Hello',
  16. ['demo:hello:hello test'],
  17. [
  18. 'php think cli demo:hello:hello test',
  19. 'php think cli demo:hello:hello test2'
  20. ]
  21. )]
  22. public function hello(Input $input, Output $output)
  23. {
  24. $output->writeln("<error>hello</error>");
  25. }
  26. }

这样我们就完整地创建了一个轻量级命令行工具demo:hello:hello