- 創(chuàng)建項目
composer create-project topthink/think tp
- 命令行創(chuàng)建自定義指令
php think make:command Hello hello
- 生成文件绊茧,加入?yún)?shù)
<?php
declare (strict_types = 1);
namespace app\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('hello')
->addArgument('name',Argument::OPTIONAL,'your name')
->addArgument('age',Argument::OPTIONAL,'your age')
->addOption('city',null,Option::VALUE_REQUIRED,'city name')
->setDescription('say hello');
}
protected function execute(Input $input, Output $output)
{
$name = $input->getArgument('name');
$name = $name ? trim($name) : 'thinkphp';
$age = $input->getArgument('age');
$age = $age ? trim($age) : '18';
if($input->hasOption('city')){
$city = PHP_EOL . 'From ' . $input->getOption('city');
}else{
$city = '';
}
// 指令輸出
$output->writeln('hello,' . $name . '!' . $city . ',年齡:'.$age);
}
}
3、配置config/console.php文件
<?php
// +----------------------------------------------------------------------
// | 控制臺配置
// +----------------------------------------------------------------------
return [
// 指令定義
'commands' => [
'hello'=>'app\command\Hello',
],
];
4、命令行執(zhí)行
php think hello 劉二狗 10 --city=深圳
5骚揍、我們測試在app\controller\Index.php中調(diào)用hello命令
<?php
namespace app\controller;
use app\BaseController;
use think\facade\Console;
class Index extends BaseController
{
public function index()
{
dump('index');
}
public function hello($name = 'ThinkPHP6',$city='北京',$age='18')
{
$output = Console::call('hello',[$name,$age,'--city='.$city]);
return $output->fetch();
}
}
6永部、運行服務(wù)
php think run
7独泞、在瀏覽器中訪問
http://127.0.0.1:8000/hello/徐鳳年?city=北涼&age=10
總結(jié):在控制器中調(diào)用命令傳遞多個參數(shù),只需要按照順序?qū)懙絚all中的第二個數(shù)組中就可以