ThinkPHP5.1 如何在控制器中调用自定义命令

前言:

业务项目开发过程中,如果是基于 ThinkPHP 框架,大部分自定义命令往往都是用于常驻内容执行一些任务,比如消费队列消息等。但是有时候,就是既想单独手动执行命令,又想在某个业务节点下触发命令。比如当项目需要迁移或者部署其他环境,所以这时候可以就需要在一些钩子或控制器中调用自定义命令了。下面就以从 MySQL 同步产品数据到 Elasticsearch 中的场景为例。

创建自定义命令:

如果在控制器调用命令需要传递参数的话,那么在创建命令时就需要显性指定参数或或者选项。特别注意的是需要引入框架 input 的 Argument 和 Option 这几个类,以下是示例代码。

<?php
/**
 * @Notes: 文件描述
 * @Interface getCondition
 * @Return mixed
 * @Author: bqs
 * @Time: 2021/4/19 15:28
 */

namespace app\common\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\console\input\Argument;
use think\console\input\Option;
use think\Db;
use think\facade\Hook;
use think\facade\Log;

class SyncProducts extends Command
{

    protected function configure()
    {
        $this->setName('sync:products')
            ->addArgument('cate_id', Argument::OPTIONAL, "分类ID")
            ->addOption('num', null, Option::VALUE_REQUIRED, '同步数量')
            ->setDescription('产品同步到Es');
    }

    protected function execute(Input $input, Output $output)
    {
        $options = $input->getOptions();
        $argurment = $input->getArguments();

        $output->writeln("!!!hello sync_products!!!". json_encode($options, JSON_UNESCAPED_UNICODE). "===参数===". json_encode($argurment, JSON_UNESCAPED_UNICODE));
    }

}

配置指令:

<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------

return [
    "app\common\command\MqttSubscribe",
    "app\common\command\MqSubscribe",
    "app\common\command\SyncProducts"
];

控制器调用:

引入 think\Console,通过 console 的静态方法 call 调用指定的自定义命令。如果需要查看命令中的打印内容,可以根据调用后返回对象的 fetch 方法查看,以下是示例代码。

public function callCommand()
{

    // 调用命令行的指令
    $output = Console::call('sync:products', ['--num', '10', "25"]);

    // 获取输出信息
    return $output->fetch();
}

执行效果:

本作品采用《CC 协议》,转载必须注明作者和本文链接
公众号: ZERO开发, 专注后端实战技术分享,致力于给猿友们提供有价值的内容。
北桥苏
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!