如何通过Laravel上的URL调用命令计划? [英] How can I call command schedule via url on the laravel?
问题描述
我使用laravel 5.6
I using laravel 5.6
我像这样在kernel.php中设置时间表:
I set my schedule in the kernel.php like this :
<?php
namespace App\Console;
use App\Console\Commands\ImportLocation;
use App\Console\Commands\ImportItem;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
protected $commands = [
ImportLocation::class,
ImportItem::class,
];
protected function schedule(Schedule $schedule)
{
$schedule->command('inspire')->dailyAt('23:00');
}
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
所以有两个命令
我将显示这样的命令之一:
I will show one of my commands like this :
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\Location;
class ImportLocation extends Command
{
protected $signature = 'import:location';
protected $description = 'import data';
public function __construct()
{
parent::__construct();
}
public function handle()
{
...
}
}
我想通过url运行命令.所以它不能在命令提示符下运行
I want to run the command via url. So it not run in the command promp
我这样尝试:
我在路由中添加了这个脚本:Route::get('artisan/{command}/{param}', 'CommandController@show');
,并制作了一个像这样的控制器:
I add this script : Route::get('artisan/{command}/{param}', 'CommandController@show');
in the routes and I make a controller like this :
namespace App\Http\Controllers;
class CommandController extends Controller
{
public function show($command, $param)
{
$artisan = \Artisan::call($command.":".$param);
$output = \Artisan::output();
return $output;
}
}
我从url这样拨打电话: http://myapp-local.test/artisan /import/location
And I call from url like this : http://myapp-local.test/artisan/import/location
有效.但是它只运行一个命令
It works. But it just run one command
我想在内核中运行所有命令.因此,运行导入位置和导入项目
I want to run all command in the kernel. So run import location and import item
我该怎么办?
推荐答案
您可以做的是在Kernel.php中注册一个自定义方法,以在受保护的$commands
数组中检索所有自定义注册的命令:
What you can do is register a custom method in your Kernel.php to retrieve all custom registered commands in the protected $commands
array:
public function getCustomCommands()
{
return $this->commands;
}
然后在您的控制器中,您可以将它们全部循环并通过Artisan的call()
或queue()
方法执行它们:
Then in your controller you can loop them all and execute them via Artisan's call()
or queue()
methods:
$customCommands = resolve(Illuminate\Contracts\Console\Kernel::class)->getCustomCommands();
foreach($customCommands as $commandClass)
{
$exitCode = \Artisan::call($commandClass);
//do your stuff further
}
您可以在文档页面上 <了解更多有关命令的信息
More on Commands you can understand on the documentation's page
这篇关于如何通过Laravel上的URL调用命令计划?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!