2

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?

Karl Hill
  • 12,937
  • 5
  • 58
  • 95
Mike Miller
  • 3,071
  • 3
  • 25
  • 32
  • Try with *use \Illuminate\Support\Facades\Response;* (notice the backslash at the beginning). Anyway, a ServiceProvider should overwrite the register method, refer to Facades on Laravel docs. – marcanuy May 25 '15 at 15:18
  • The error is related to the class I have created not the class I have used. I dont think there is an issue with this. Also the `ProviderRepository.php` reference relates back to the inclusion of my new class in the `config\app.php` file I think – Mike Miller May 25 '15 at 15:25
  • OK got you. I am wrong to try and load the extension as a service provider. Makes sense. I just need to be able to use this class. Doesnt matter what I try it still tells me the class cannot be found! Damned PHP namespaces they always give me a headache – Mike Miller May 25 '15 at 15:45
  • This has nothing to do directly with your problem, but you might want to take a look at [Response Macros](http://laravel.com/docs/5.0/responses#response-macros) – lukasgeiter May 25 '15 at 16:13
  • Yeah I am actually using this approach and is a solid suggestion. For academic reasons would still like to figure this mo fo out – Mike Miller May 25 '15 at 16:31
  • What do you have in **in ProviderRepository.php line 150**? – marcanuy May 25 '15 at 16:49

1 Answers1

3

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',
Sh1d0w
  • 9,340
  • 3
  • 24
  • 35