共计 1658 个字符,预计需要花费 5 分钟才能阅读完成。
今天使用 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"
库安装完后,我们访问试试:
很简单吧,这样就可以啦~~
特别提示:
本人正在培养自己的写作水平,会把平时遇到的问题和有趣的东西记录下来,如果对你有帮助请动动小手点个赞支持支持,大神莫喷,谢谢!!
正文完