通过命令行调用 Laravel 控制器 [英] Call laravel controller via command line
问题描述
在 kohana 框架中,我可以使用命令行调用控制器
In kohana framework I can call controller via command line using
php5 index.php --uri=controller/method/var1/var2
是否可以通过 cli 在 Laravel 5 中调用我想要的控制器?如果是,该怎么做?
Is it possible to call controller I want in Laravel 5 via cli? If yes, how to do this?
推荐答案
目前没有办法(不确定是否会有).但是,您可以创建自己的 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.
这篇关于通过命令行调用 Laravel 控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!