且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过命令行调用 Laravel 控制器

更新时间:2023-02-22 11:02:18

目前没有办法(不确定是否会有).但是,您可以创建自己的 Artisan Command 来做到这一点.使用以下命令创建命令 CallRoute:

There is no way so far (not sure if there will ever be). However you can create your own Artisan Command that can do that. Create a command CallRoute using this:

php artisan make:console CallRoute

对于 Laravel 5.3 或更高版本,您需要使用 make:command 代替:

For Laravel 5.3 or greater you need to use make:command instead:

php artisan make:command CallRoute

这将在 app/Console/Commands/CallRoute.php 中生成一个命令类.该类的内容应如下所示:

This will generate a command class in app/Console/Commands/CallRoute.php. The contents of that class should look like this:

<?php namespace AppConsoleCommands;

use IlluminateConsoleCommand;
use SymfonyComponentConsoleInputInputOption;
use IlluminateHttpRequest;

class CallRoute extends Command {

    protected $name = 'route:call';
    protected $description = 'Call route from CLI';

    public function __construct()
    {
        parent::__construct();
    }

    public function fire()
    {
        $request = Request::create($this->option('uri'), 'GET');
        $this->info(app()['IlluminateContractsHttpKernel']->handle($request));
    }

    protected function getOptions()
    {
        return [
            ['uri', null, InputOption::VALUE_REQUIRED, 'The path of the route to be called', null],
        ];
    }

}

然后您需要通过将其添加到app/Console/Kernel.php 中的$commands 数组来注册命令:

You then need to register the command by adding it to the $commands array in app/Console/Kernel.php:

protected $commands = [
    ...,
    'AppConsoleCommandsCallRoute',
];

您现在可以使用以下命令调用任何route:

You can now call any route by using this command:

php artisan route:call --uri=/route/path/with/param

请注意,此命令将返回一个响应,因为它会发送到浏览器,这意味着它在输出的顶部包含 HTTP 标头.

Mind you, this command will return a response as it would be sent to the browser, that means it includes the HTTP headers at the top of the output.