thinkphp6.0在控制器中调用命令,如何传多个参数

来源:WX部落

thinkphp6.0自定义命令,在控制器中调用的时候,如何传多个参数

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中的第二个数组中就可以

声明:

① 凡本网所有原创文章及图片、图表的版权均属WX部落所有,如需转载,需注明“信息来源:WX部落”,并且添加本文地址:http://wxbuluo.com/index/article/39.html

② 凡本网注明“来源:XXX(非WX部落)”的文字及图片内容,均转载自其他媒体,版权归原媒体及作者所有。转载目的在于传递更多的资讯,并不代表本网赞同其观点和对其真实性负责。如有侵权,请联系删除。联系方式:296720094@qq.com

③ 本网站的资源部分内容来源于网络,仅供大家学习与参考,如有侵权,请联系站长296720094@qq.com进行删除处理。

④ 部分项目课程具有时效性,如发布时间较长请搜索相关课程选择发布时间最近的查看。

⑤ 部分具有时效性的项目课程文章,我们会逐步转移到免费类分类开放下载。同时免费分类链接失效不补!

⑥ 本站资源大多存储在云盘,如发现链接失效,请联系我们我们会第一时间更新。