Laravel7 通过命令行 Command 执行控制器的方法

  1. 创建命令类

php artisan make:command Action

  1. app\Console\Commands 目录下找到Action.php, 粘贴以下代码
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Exception;

class Action extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'action:call {class_method} {--params=*}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '执行控制器的方法';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }


    /**
     * 可变数量的参数...
     * $result = $app->$method(...$params);
     *
     * Example:
     * [json]
     * command: php artisan action:call xxxController@xxxMethod --params='{\"name\":\"xiaoming\"}'
     *
     * [多参数]
     * command: php artisan action:call xxxController@xxxMethod --params='2023-03-14' --params='2023-03-14'
     * ```
     */
    public function handle()
    {
        try {
            $class_method = $this->argument('class_method');

            $params = $this->option('params');

            $params = array_map(function ($v) {
                return $this->is_json($v) ? json_decode($v, true) : $v;
            }, $params);

            [$class, $method] = explode('@', $class_method);

            if (empty($class) || empty($method)) {
                throw new Exception('The format (Controller@method) is required');
            }

            $app = app("App\Http\Controllers\\" . $class);

            if (!method_exists($app, $method)) {
                throw new Exception('Method not exists');
            }

            $result = $app->$method(...$params);

            $this->info($result);
        } catch (Exception $e) {
            $this->info($e->getMessage());
        }
    }


    /**
     * is json
     * @param $string
     * @return bool
     */
    private function is_json($string): bool
    {
        if (is_string($string)) {
            json_decode($string);
            return (json_last_error() === JSON_ERROR_NONE);
        }
        return false;
    }
}

  1. app/Console/Kernel.php 中的 $commands 增加该命令类
 protected $commands = [
 	 ...,
    'App\Console\Commands\Action',
 ];
  1. 如何执行
[json]
command: php artisan action:call xxxController@xxxMethod --params='{\"name\":\"xiaoming\"}'

[多参数]
command: php artisan action:call xxxController@xxxMethod --params='2023-03-14' --params='2023-03-14'

xxxController 代表是控制器,xxxMethod是控制器某个方法
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值