[自定义插件命令行]

第一步,我们以demo插件为例创建plugin:hello命令行,在public/plugins/demo/command目录里创建Hello.php文件

  1. <?php
  2. namespace plugins\demo\command;
  3. use think\console\Command;
  4. use think\console\Input;
  5. use think\console\input\Argument;
  6. use think\console\input\Option;
  7. use think\console\Output;
  8. class Hello extends Command
  9. {
  10. protected function configure()
  11. {
  12. $this->setName('plugin:hello')
  13. ->addArgument('name', Argument::OPTIONAL, "your name")
  14. ->addOption('city', '-c', Option::VALUE_REQUIRED, 'city name')
  15. ->setDescription('Say Plugin Hello');
  16. }
  17. protected function execute(Input $input, Output $output)
  18. {
  19. $name = $input->getArgument('name');
  20. $name = $name ? $name : 'ThinkCMF';
  21. $city = $input->getOption('city');
  22. $city = $city ? $city : 'China';
  23. $output->writeln("Hello, My name is " . $name . '! I\'m from ' . $city);
  24. }
  25. }

这个文件定义了一个叫plugin:hello的命令,并设置了一个name参数和一个city选项。

第二步,我们创建命令行配置文件public/plugins/demo/command.php,并添加如下内容

  1. <?php
  2. return [
  3. // 指令名 =》完整的类名
  4. 'plugin:hello' => 'plugins\demo\command\Hello'
  5. ];

第三步,测试-命令帮助-命令行下运行

  1. php think

输出

  1. ThinkPHP v6.0.12LTS & ThinkCMF v6.0.5
  2. Usage:
  3. command [options] [arguments]
  4. Options:
  5. -h, --help Display this help message
  6. -V, --version Display this console version
  7. -q, --quiet Do not output any message
  8. --ansi Force ANSI output
  9. --no-ansi Disable ANSI output
  10. -n, --no-interaction Do not ask any interactive question
  11. -v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
  12. Available commands:
  13. clear Clear runtime file
  14. cli List lightweight CLI commands
  15. help Displays help for a command
  16. list Lists commands
  17. run PHP Built-in Server for ThinkPHP
  18. version Show ThinkPHP & ThinkCMF version
  19. demo
  20. demo:hello Say App Hello
  21. migrate
  22. migrate:create Create a new migration
  23. migrate:run Execute database migration
  24. plugin
  25. plugin:hello Say Plugin Hello
  26. publish
  27. publish:app Publish a ThinkCMF app
  28. publish:plugin Publish a ThinkCMF plugin
  29. publish:theme Publish a ThinkCMF theme
  30. service
  31. service:discover Discover Services for ThinkPHP
  32. vendor
  33. vendor:publish Publish any publishable assets from vendor packages

第四步,运行plugin:hello命令

  1. php think plugin:hello

输出

  1. Hello, My name is ThinkCMF! I'm from China

添加命令参数

  1. php think plugin:hello catman

输出

  1. Hello, My name is catman! I'm from China

添加city选项

  1. php think plugin:hello --city Shanghai

输出

  1. Hello, My name is ThinkCMF! I'm from Shanghai