Facades
介绍
Facades 提供了一种“静态”接口来获得服务容器中可用的类。Laravel 提供多种 Facades,你很有可能在还不知道它的情况下已经在使用它们了!Laravel 的 “facades” 作为服务容器中基础类的静态代理,具有简洁,意图明确的语法,同时比传统的静态方法更具易测性和灵活性。
使用 Facades
在 Laravel 应用程序的环境中,facade 是一个从容器中获取某个对象的类。Facade 让整个机制得以运转。Laravel 的 facades 以及任何你自定义的 facades,都都继承自基类 Illuminate\Support\Facades\Facade。
一个 facade 类只需要实现一个方法: getFacadeAccessor。 getFacadeAccessor 方法的任务就是定义在容器做什么解析。Facade的基类使用 __callStatic()魔术方法从你的 facade 中获得解析完成后的对象。
下面的例子中,我们对Laravel的缓存系统进行了一次调用。初看这段代码,有人可能认为 Cache 类调用了 get 静态方法:
<?phpnamespace App\Http\Controllers;use Cache;use App\Http\Controllers\Controller;class UserController extends Controller{/*** Show the profile for the given user.** @param int $id* @return Response*/public function showProfile($id){$user = Cache::get('user:'.$id);return view('profile', ['user' => $user]);}}
注意在靠近文件的顶部我们引入了 Cache facade。该 facade 作为一个获取 Illuminate\Contracts\Cache\Factory 的基础实现的代理。所有使用该 facade 的调用都会被传递给 Laravel 缓存服务的实例。
我们来看一下 Illuminate\Support\Facades\Cache 类, 你会发现它并没有 get 静态方法:
class Cache extends Facade{/*** Get the registered name of the component.** @return string*/protected static function getFacadeAccessor() { return 'cache'; }}
相反地, Cache facade 继承了 Facade 基类并且定义了一个 getFacadeAccessor() 方法。请记住,该方法的任务只是返回一个服务容器的名字。每当用户引用任意 Cache facade的静态方法,Laravel将解析出 服务容器 中名为 cache 的绑定对象,并且在该实例中执行所请求的方法(在此例中为 get)。
Facade 类参考
你可以下面的表单中找到所有的 facade 以及它的基类。它对于快速深入了解某个facade的API文档很有用。它同时还包含了各个facade的服务容器绑定。
