-->

Extend Laravel 5 Response Facade

2019-04-14 06:23发布

问题:

I am getting a namespacing issue when trying to extend the Response facade in Laravel 5. I have created a new folder tree under the app directory called Extensions\Facades. In this folder I have a file called AjaxResponse.php which has the following contents:

<?php namespace App\Extensions\Facades;

use Illuminate\Support\Facades\Response;

class AjaxResponse extends Response{

    public static function send($code,$body,$http_code=200){

        parent::json( array(
                'status'=>(string)$code,
                'body' =>$body
            ) )->setStatusCode($http_code)->send();
        exit();

    }
}

I am registering this as a service provider in config/app.php like I understand I am supposed to:

providers=[
            //..normal stuff
            'App\Extensions\Facades\AjaxResponse',
]

And this is throwing the normal namespace error of class not found:

FatalErrorException in ProviderRepository.php line 150: 
Class 'App\Extensions\Facades\AjaxResponse' not found

Can anyone shed any light on why the class is not found?

回答1:

Go to project root folder and in the terminal type

composer dump-autoload

Everything should be fine then. When you create a new folder, composer does not know about it, so it can not autoload files from it, even if they are psr-4 namespaced.

EDIT Also you need to declare alias for your facade in config/app.php under aliases array, not the providers one:

 'AjaxResponse'   => 'App\Extensions\Facades\AjaxResponse',