且构网

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

通过命令行调用laravel控制器

更新时间:2023-02-22 11:07:12

到目前为止,还没有办法(不确定是否会出现).但是,您可以创建自己的 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 App\Console\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Illuminate\Http\Request;

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()['Illuminate\Contracts\Http\Kernel']->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 = [
    ...,
    'App\Console\Commands\CallRoute',
];

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

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.