Laravel: Difference between Facades and Aliases
很好的一天!
我读得越多,对这件事就越感到困惑。外观和别名有什么区别?
我有这门课:
/app/库/project/data.php
1 2 3 4 5 6 7 | namespace PJ; class Data { // It is much like a data container, with static methods and properties for saving info } |
以及相应的门面,所以我可以只使用pjd::。
根据周围的网页:
... Laravel Facades are proxies. They wrap around and call functions
on the underlying true implementation of the code. Further, in the
context of a Laravel application, these Facades are accessed by
assigning them to aliases. This use of the Dependency Injection
container allow you to reference something like
Illuminate\Support\Facades\Filesystem by simply calling File.
(http://ryantablada.com/post/proxies-service-locators-alias-facades-and-war)
但是,我也发现并成功地测试了添加如下内容:
_ app/config/app.php应用程序__
1 2 3 4 |
我也可以用同样的方式进入我的班级。
那么,有什么区别呢?
谢谢
编辑第01页
我在/app/libraries/project/data.php中创建了一个名为data的类。
1 2 3 4 5 | namespace PJ; class Data { // It is much like a data container, with static methods and properties for saving info } |
我有一个facade类用于这个类data/app/libraries/project/datafacade.php
1 2 3 4 5 6 | use Illuminate\Support\Facades\Facade; class PJD extends Facade { protected static function getFacadeAccessor() { return 'PJData'; } } |
我为他们提供了一个服务提供商:app/libraries/project/dataserviceprovider.php
1 2 3 4 5 6 7 8 9 | use Illuminate\Support\ServiceProvider; class DataServiceProvider extends ServiceProvider { public function register() { $this->app->singleton('PJData', function() { return new PJ\Data; }); } } |
我还添加了/app/config/app.php:
1 2 3 4 |
在composer.json中,我添加了一个psr-4行来将pj名称空间定向到/app/libraries/project
1 2 3 | "psr-4": { "PJ\":"app/libraries/Project" }, |
通过这样做,我可以通过pjd::而不是pjdata::,从项目中的任何地方访问我的类。
不过,我也注意到,只需添加到/app/config/app.php
1 2 3 4 |
我得到的结果完全相同,没有所有的外观和服务提供商。那么,有什么意义呢?
谢谢,对这篇大文章感到抱歉。
Facade和Alias是两个完全不同的概念。
您不能通过
如果您正在访问它,而没有在config/app.php中定义它,那么您已经在服务提供者文件中设置了它。
别名的定义,
used to indicate that a named person is also known or more familiar under another specified name.
它只意味着你给这个类取了一个不同的名字,这样它就更容易调用了。
例如
如果您有这样一个类:
注:
Unit testing is an important aspect of why facades work the way that they do. In fact, testability is the primary reason for facades to even exist.