Lumen 報錯提示 例項不了 Response 類的問題

NaturalGao發表於2019-05-15
今天使用Lumen的時候,用到了Response類,很奇怪提示:Target [Illuminate\Contracts\Routing\ResponseFactory] is not instantiable.

大概就是說例項不了Response 類,那怎麼解決呢?我們以一個全新的Lumen專案來說
<?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);
});

然後訪問這個路由報錯如下(也就是我們要解決的錯誤):

Lumen報錯提示 例項不了Response類的問題

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"

庫安裝完後,我們訪問試試:

Lumen報錯提示 例項不了Response類的問題

很簡單吧,這樣就可以啦~~

特別提示:

本人正在培養自己的寫作水平,會把平時遇到的問題和有趣的東西記錄下來,如果對你有幫助請動動小手點個贊支援支援,大神莫噴,謝謝!!

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章