[自定义插件命令行]
第一步,我们以demo插件为例创建plugin:hello命令行,在public/plugins/demo/command目录里创建Hello.php文件
<?phpnamespace plugins\demo\command;use think\console\Command;use think\console\Input;use think\console\input\Argument;use think\console\input\Option;use think\console\Output;class Hello extends Command{protected function configure(){$this->setName('plugin:hello')->addArgument('name', Argument::OPTIONAL, "your name")->addOption('city', '-c', Option::VALUE_REQUIRED, 'city name')->setDescription('Say Plugin Hello');}protected function execute(Input $input, Output $output){$name = $input->getArgument('name');$name = $name ? $name : 'ThinkCMF';$city = $input->getOption('city');$city = $city ? $city : 'China';$output->writeln("Hello, My name is " . $name . '! I\'m from ' . $city);}}
这个文件定义了一个叫plugin:hello的命令,并设置了一个name参数和一个city选项。
第二步,我们创建命令行配置文件public/plugins/demo/command.php,并添加如下内容
<?phpreturn [// 指令名 =》完整的类名'plugin:hello' => 'plugins\demo\command\Hello'];
第三步,测试-命令帮助-命令行下运行
php think
输出
ThinkPHP v6.0.12LTS & ThinkCMF v6.0.5Usage:command [options] [arguments]Options:-h, --help Display this help message-V, --version Display this console version-q, --quiet Do not output any message--ansi Force ANSI output--no-ansi Disable ANSI output-n, --no-interaction Do not ask any interactive question-v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debugAvailable commands:clear Clear runtime filecli List lightweight CLI commandshelp Displays help for a commandlist Lists commandsrun PHP Built-in Server for ThinkPHPversion Show ThinkPHP & ThinkCMF versiondemodemo:hello Say App Hellomigratemigrate:create Create a new migrationmigrate:run Execute database migrationpluginplugin:hello Say Plugin Hellopublishpublish:app Publish a ThinkCMF apppublish:plugin Publish a ThinkCMF pluginpublish:theme Publish a ThinkCMF themeserviceservice:discover Discover Services for ThinkPHPvendorvendor:publish Publish any publishable assets from vendor packages
第四步,运行plugin:hello命令
php think plugin:hello
输出
Hello, My name is ThinkCMF! I'm from China
添加命令参数
php think plugin:hello catman
输出
Hello, My name is catman! I'm from China
添加city选项
php think plugin:hello --city Shanghai
输出
Hello, My name is ThinkCMF! I'm from Shanghai
