今天使用Lumen的时候,用到了Response类,很奇怪提示:Target [Illuminate\Contracts\Routing\ResponseFactory] is not instantiable.
大概就是说实例不了Response 类,那怎么解决呢?我们以一个全新的Lumen项目来说
1.我在web.php写了个路由
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It is a breeze. Simply tell Lumen the URIs it should respond to
| and give it the Closure to call when that URI is requested.
|
*/
use Illuminate\Support\Facades\Response;
$router->get('/', function () use ($router) {
return Response::json('123456',200);
});
然后访问这个路由报错如下(也就是我们要解决的错误):
2.解决办法
2.1 打开项目根目录下的 bootstrap/app.php
//找到这两行把注释去掉
$app->withFacades();
$app->register(App\Providers\AppServiceProvider::class);
2.2 找到 项目根目录下的 app/Providers/AppServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Routing\ResponseFactory;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
}
}
在 register 注册 ResponseFactory 修改如下:
<?php
namespace App\Providers;
use Illuminate\Routing\ResponseFactory;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->app->singleton('Illuminate\Contracts\Routing\ResponseFactory', function ($app)
{
return new ResponseFactory(
$app['Illuminate\Contracts\View\Factory'],
$app['Illuminate\Routing\Redirector']);
});
}
}
这时候还不行, 我们还需要安装一个 库,切换到项目根目录 执行composer命令:
composer require "illuminate/routing"
库安装完后,我们访问试试:
很简单吧,这样就可以啦~~
特别提示:
本人正在培养自己的写作水平,会把平时遇到的问题和有趣的东西记录下来,如果对你有帮助请动动小手点个赞支持支持,大神莫喷,谢谢!!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。