- 创建命令类
php artisan make:command Action
- 在 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;
}
}
- 在 app/Console/Kernel.php 中的 $commands 增加该命令类
protected $commands = [
...,
'App\Console\Commands\Action',
];
- 如何执行
[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是控制器某个方法