Lumen error indicates that the instance cannot respond

When using Lumen today, the Response class is used. It's strange to notice that Target [Illuminate\Contracts\Routing\ResponseFactory] is not instantiable

That is to say, the instance cannot have the Response class, so how to solve it? For a brand new Lumen project

1. I wrote a route in 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);
});

Then access this route and report an error as follows (that is, the error we want to solve):

2. Solutions

2.1 open bootstrap/app.php in the root directory of the project

//Find these two lines and get rid of the comments
 $app->withFacades();  
 $app->register(App\Providers\AppServiceProvider::class);

2.2 find app/Providers/AppServiceProvider.php under the project root directory

<?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 in register and modify it as follows:

<?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']);
        });
    }
}

At this time, we need to install a library and switch to the root directory of the project to execute the composer command:

composer require "illuminate/routing"

After the library is installed, let's visit:

It's very simple, so it's ok~~

Special tips:

I'm developing my writing skills, and I will record the problems and interesting things I encounter at ordinary times. If it's helpful to you, please give me a little praise and support. Don't spray. Thank you!!

Tags: PHP JSON

Posted on Sun, 10 Nov 2019 06:38:09 -0800 by eddjc