如何理解Laravel门面门面模式也叫外观模式,Laravel的门面为服务提供了一个「静态」代理,相比于传统用法,使用时更加灵活,语法更加简明优雅。举个例子,假如我们绑定了一个服务,传统方式会用以下方式调用服务:class CacheService{ public function get() { return ‘从缓存中获取数据’; }}// 绑定服务$container->singleton(‘cache’, function(){ return new CacheService();});// 从容器中获取服务$cache = $container->make(‘cache’);$value = $cache->get();var_dump($value);用门面模式做静态代理:$value = Cache::get();var_dump($value);Cache类就是cache服务的静态代理,也可以说Cache类就是cache服务的门面。通过调用静态方法Cache::get(),就能直接调用到cache服务中的get方法。我们看一下Cache是如何实现静态代理的,非常简单:class Cache{ // cache服务实例 protected static $instance; protected static function getFacadeAccessor() { // 返回服务名 return ‘cache’; } public static function __callStatic($name, $arguments) { if (is_null(static::$instance)) { // 根据服务名从容器中寻找服务 static::$instance = app(static::getFacadeAccessor()); } // 调用服务方法 return call_user_func_array([static::$instance, $name], $arguments); }}