通过命令行调用 Laravel 控制器
在Laravel框架中,目前还没有直接通过命令行调用控制器的方法(不确定以后是否会有)。但是可以通过自定义Artisan命令来实现这个功能。可以使用以下命令创建一个CallRoute命令:
php artisan make:console CallRoute
对于Laravel 5.3或更高版本,需要使用make:command命令:
php artisan make:command CallRoute
这将在app/Console/Commands/目录下生成一个CallRoute.php的命令类。其内容如下:
option('uri'), 'GET'); $this->info(app()->make(\Illuminate\Contracts\Http\Kernel::class)->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数组中:
protected $commands = [ ..., 'App\Console\Commands\CallRoute', ];
现在可以通过以下命令来调用任何路由:
php artisan route:call --uri=/route/path/with/param
需要注意的是,这个命令将返回一个响应,就像它将发送给浏览器一样,这意味着它包括输出的顶部的HTTP头信息。
对于Laravel 4,请使用命令`php artisan command:make CallRoute`。内核实际上就是路由器,所以命令需要使用`$this->info(app()[\Illuminate\Routing\Router::class]->handle($request));`。将该命令添加到artisan中,可以在app/start/artisan.php文件中使用`Artisan::add(new CallRoute);`。
对于Laravel 5.4,上述解决方法似乎已经不再适用,会报错"Target [\Illuminate\Contracts\Http\Kernel] is not instantiable."。找到一个解决方法,将`app()['Illuminate\Contracts\Http\Kernel']`改为`app()->make(\Illuminate\Contracts\Http\Kernel::class)`。
问题:如何通过命令行调用Laravel控制器?
原因:使用Laravel 5.0时,通过以下代码触发控制器:
$ php artisan tinker $ $controller = app()->make('App\Http\Controllers\MyController'); $ app()->call([$controller, 'myMethodName'], []);
在`app()->call()`的最后一个`[]`中可以传递参数,例如`[user_id] => 10`等。
解决方法:可以通过自定义Artisan命令来实现非交互调用,具体步骤可参考[Laravel官方文档](https://laravel.com/docs/5.4/artisan#writing-commands)。通过创建一个命令,你可以使用`php artisan mycommand`来运行命令,而不是使用`tinker`。
补充说明:`tinker`是一个Artisan命令,它打开一个会话,让你与Laravel进行交互。`app()`返回应用程序实例。以上代码是3个独立的命令,可以通过`$controller->someFunction()`来简化`app()->call([$controller, 'myMethodName'], [])`的写法。
问题出现的原因是在Lumen中调用Laravel控制器时出现了错误。解决方法是在app/Console/Commands/CallRoute.php
文件中添加一个命令类,并在app/Console/Kernel.php
文件中注册该命令类。然后使用php artisan route:call /path
命令来调用控制器。
在Laravel 5.4中,首先使用php artisan make:command CallRoute
命令生成一个命令类CallRoute
。接着在app/Console/Commands/CallRoute.php
文件中添加以下代码:
namespace App\Console\Commands; use Illuminate\Console\Command; use Illuminate\Http\Request; class CallRoute extends Command { protected $signature = 'route:call {uri}'; protected $description = 'php artsian route:call /route'; public function __construct() { parent::__construct(); } public function handle() { $request = Request::create($this->argument('uri'), 'GET'); $this->info(app()->make(\Illuminate\Contracts\Http\Kernel::class)->handle($request)); } }
然后在app/Console/Kernel.php
文件中添加以下代码:
protected $commands = [ 'App\Console\Commands\CallRoute' ];
最后,使用php artisan route:call /path
命令来调用控制器。
在Lumen中,上述方法会生成一个错误信息Target [Illuminate\Contracts\Http\Kernel] is not instantiable
。解决方法是将'App\Console\Commands\CallRoute'
添加到$commands
数组中的config/tinker.php
配置文件中,这样就可以在tinker中运行该命令。
这个解决方法同样适用于Laravel 5.5和Laravel 5.6。这是一个非常优雅的解决方案,比预期的解决方法更好。