thinkphp6.0官网手册中,关于自定义指令一章,只给出了一个传一个参数的实例,本文主要讲解,如何在命令行和控制器中调用命令时,传递多个参数的使用方法
1、首先安装一个项目
composer create-project topthink/think tp
2、创建一个自定义指令
php think make:command Hello hello
3、会生成一个app\command\Hello命令行指令类,我们将官方提供的实例代码稍加修改,再添加一个参数
<?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);
}
}
4、配置config/console.php文件
<?php
// +----------------------------------------------------------------------
// | 控制台配置
// +----------------------------------------------------------------------
return [
// 指令定义
'commands' => [
'hello'=>'app\command\Hello',
],
];
5、命令行执行
php think hello 陈宁 10 --city=北京
6、我们测试在app\controller\Index.php中调用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();
}
}
7、运行服务
php think run
8、在浏览器中访问
http://127.0.0.1:8000/hello/陈宁?city=北京&age=10
总结:在控制器中调用命令传递多个参数,只需要按照顺序写到call中的第二个数组中就可以