Laravel 5使用声明 [英] Laravel 5 use statements
问题描述
首次使用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
也许我想念什么?这些类似乎是框架的一部分,默认在L4.x中.
Maybe I'm missing something?? These classes seem to be part of the framework, and were by default in L4.x.
任何人都可以帮助我了解为什么在L5中会出现这种情况,或者如何避免使用L5这样做吗?
Can anyone help me understand why this is so in L5 or how I can avoid having to do this with L5?
Google在这方面使我失败了.
The Googles have failed me on this one.
推荐答案
在文件中使用use
语句的过程称为别名或导入. http://php.net/manual/en/language.namespaces.importing.php 对此做了很好的解释,但总之:
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:
- 如果您使用相对"或仅使用类名(例如
Session
)引用类,则PHP将检查当前名称空间中该类是否存在. - Laravel 4控制器在技术上不在名称空间中.它们是应用程序的根名称空间的一部分,因此对根名称空间(
Session
)中的另一个类的引用就可以找到该名称. Laravel 5控制器在App\Http\Controllers\
中命名空间. - 解决此问题的唯一方法是告诉PHP给定类的完整名称空间,例如本例中的
\Session
,因为这些类是作为根名称空间的一部分添加的.例如new \App\MyCompany\Models\SomeModel();
- 类文件顶部的"use"语句使您可以为所有完整的类路径加上别名,以备不时之需.
use \App\MyCompany\Models\SomeModel as Foo
允许您执行new Foo()
并获取\App\MyCompany\Models\SomeModel
的实例. (大多数会省略'as'语句,而仅引用new SomeModel()
) - 在尝试利用与当前类位于不同名称空间中的类时,没有办法,也不必尝试避免将这些
use
语句添加到您的类中.这是一种有用的语言构造,而不是一种限制.
- 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 inApp\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 likenew \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 donew Foo()
and get an instance of\App\MyCompany\Models\SomeModel
. (Most would leave off the 'as' statement, and just referencenew 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.
希望如此.
这篇关于Laravel 5使用声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!