Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 use statements [duplicate]

Tags:

php

laravel-5

Working with Laravel 5 for the first time. I understand the use of namespaces and why you need to use them. What I don't understand is why I need to add use statements like the following (at the top of a controller):

use Session;
use Input;
use Response;

I have to do this so that I don't get fatal exceptions like:

Class 'App\Http\Controllers\Session' not found

Maybe I'm missing something?? These classes seem to be part of the framework, and were by default in L4.x.

Can anyone help me understand why this is so in L5 or how I can avoid having to do this with L5?

The Googles have failed me on this one.

like image 432
Joel Leger Avatar asked Mar 12 '15 03:03

Joel Leger


1 Answers

The process of using use statements in files is called aliasing or importing. http://php.net/manual/en/language.namespaces.importing.php gives a good explanation of it, but in short:

  • If you reference a class using a 'relative' or just the class's name(Such as Session), PHP is going to check the current namespace for the existence of that class.
  • Laravel 4 controllers were not technically in a namespace. They were part of the root namespace of the application, and therefor a reference to another class in the root namespace (Session) would find just that. Laravel 5 controllers are namespaced in App\Http\Controllers\.
  • The only way to solve this is to tell PHP the full namespace of a given class, such as in this case \Session, as these classes are added as part of the root namespace. An example would be something like new \App\MyCompany\Models\SomeModel();
  • The "use" statements at the top of a class file allow you to alias these full class-paths as anything you want. use \App\MyCompany\Models\SomeModel as Foo would allow you to do new Foo() and get an instance of \App\MyCompany\Models\SomeModel. (Most would leave off the 'as' statement, and just reference new SomeModel())
  • There is no way, nor need to try, to avoid adding these use statements to your classes when trying to leverage classes that are in a different namespace from the current class. It is a useful construct of the language, and not a limitation.

Hope that makes sense.

like image 94
V13Axel Avatar answered Nov 06 '22 07:11

V13Axel