首页 > 解决方案 > 如何通过 laravel 上的 url 调用命令计划?

问题描述

我使用 laravel 5.6

我在 kernel.php 中设置了我的时间表,如下所示:

<?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');
    }
}

所以有两个命令

我将展示我的一个命令,如下所示:

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 运行命令。所以它不在命令提示符中运行

我尝试这样:

我添加了这个脚本:Route::get('artisan/{command}/{param}', 'CommandController@show'); 在路线中,我制作了一个这样的控制器:

namespace App\Http\Controllers;
class CommandController extends Controller
{
    public function show($command, $param)
    {
        $artisan = \Artisan::call($command.":".$param);
        $output = \Artisan::output();
        return $output;
    }
}

我从这样的网址调用:http://myapp-local.test/artisan/import/location

有用。但它只运行一个命令

我想在内核中运行所有命令。所以运行导入位置和导入项目

我该怎么做?

标签: laravellaravel-5commandlaravel-5.6schedule

解决方案


您可以做的是在您的 Kernel.php 中注册一个自定义方法来检索受保护$commands数组中的所有自定义注册命令:

public function getCustomCommands()
{
    return $this->commands;
}

然后在您的控制器中,您可以将它们全部循环并通过 Artisancall()queue()方法执行它们:

$customCommands = resolve(Illuminate\Contracts\Console\Kernel::class)->getCustomCommands();

foreach($customCommands as $commandClass)
{
    $exitCode = \Artisan::call($commandClass);
    //do your stuff further
}

有关您可以在文档页面上理解的命令的更多信息


推荐阅读