感謝https://blog.csdn.net/kelinfeng16/article/details/88549717
先簡單的定義一個命令,建立一個命令行測試類:
<php?
namespace app\base\command; use think\console\Command; use think\console\Input; use think\console\Output; class Test extends Command { protected function configure() { $this->setName('test');//定義命令的名字 } protected function execute(Input $input, Output $output) { $output->writeln('Hello World');//在命令行界面輸出內容 } }
現在來說一下這2個方法的功能:
configure()
用來設置自定義命令屬性,可以配置命令名字、命令參數、命令選項、命令描述
execute()
用來設置執行命令的相關操作,通過Input,Output輸入輸出達到命令行和代碼的交互。
配置命令
設置完了自定義命令,還要在application/command.php中配置一下才行哦:
<php?
return [ 'app\base\command\Test' ];
一個命令對應一個命令類,對應一個配置。也就是說想定義多個命令,就需要建立多個類文件,每個定義的命令都要在這里配置才能生效。
到網站根目錄,執行
php think
能查看所有可用的命令
執行
php think test
就會輸出
Hello World
--------------------------------------------
命令參數
上面的命令似乎只能執行一些簡單的操作,這次我們給命令添加幾個參數,增加命令的功能性。
<?php protected function configure() { $this->setName('test') //定義命令的名字 ->setDescription('This is my command') //定義命令的描述 ->addArgument('name') //增加一個名字參數 ->addArgument('age'); //增加一個年齡參數 } protected function execute(Input $input, Output $output) { //獲取輸入的參數 $name = $input->getArgument('name'); $age = $input->getArgument('age'); //輸出獲得的參數 $output->writeln("My name is $name ,age is $age"); }
執行命令
php think test wuhen 20
獲得
My name is wuhen,age is 20 的輸出
---------------------------------------------------------------
命令選項
我們的命令雖然可以傳入參數了,不過可以增加 選項 進一步充分我們命令的功能。
<?php protected function configure() { $this->setName('calculate') //定義命令的名字 ->setDescription('This is my command') //定義命令的描述 ->addArgument('number1') //參數1 ->addArgument('number2') //參數2 ->addOption('add') //定義相加的選項 ->addOption('sub'); //定義相減的選項 } protected function execute(Input $input, Output $output) { //獲取輸入的2個參數 $number1 = $input->getArgument('number1'); $number2 = $input->getArgument('number2'); //加法操作 if($input->hasOption('add')){ $result = $number1 + $number2; $output->writeln("$number1 + $number2 = $result"); } //減法操作 if($input->hasOption('sub')){ $result = $number1 - $number2; $output->writeln("$number1 - $number2 = $result"); } }
在命令行輸入:
php think calculate 20 30 --add
可以看到返回 :
20 + 30 = 50
在命令行輸入:
php think calculate 20 30 --sub
可以看到返回:
20 - 30 = -10
選項也是可以設置默認值和執行命令時添加值的,例如
<?php protected function configure() { $this->setName('test') ->addOption( "port", null, Option::VALUE_REQUIRED, '', 9501 ) ->setDescription('test is a test function '); } protected function execute(Input $input, Output $output) { $port = $input->getOption('port'); $output->writeln("TestCommand:".$port); }
執行命令
php think test --port
或者執行命令
php think test --port=555
試試看吧