什么是Facades

Facades是我们在Laravel应用开发中使用频率很高的一个组件,叫组件不太合适,其实它们是一组静态类接口或者说代理,让开发者能简单的访问绑定到服务容器里的各种服务。Laravel文档中对Facades的解释如下:

Facades 为应用程序的 服务容器 中可用的类提供了一个「静态」接口。Laravel 本身附带许多的 facades,甚至你可能在不知情的状况下已经在使用他们!Laravel 「facades」作为在服务容器内基类的「静态代理」,拥有简洁、易表达的语法优点,同时维持着比传统静态方法更高的可测试性和灵活性。

我们经常用的Route就是一个Facade, 它是\Illuminate\Support\Facades\Route类的别名,这个Facade类代理的是注册到服务容器里的router服务,所以通过Route类我们就能够方便地使用router服务中提供的各种服务,而其中涉及到的服务解析完全是隐式地由Laravel完成的,这在一定程度上让应用程序代码变的简洁了不少。下面我们会大概看一下Facades从被注册进Laravel框架到被应用程序使用这中间的流程。Facades是和ServiceProvider紧密配合的所以如果你了解了中间的这些流程对开发自定义Laravel组件会很有帮助。

注册Facades

说到Facades注册又要回到再介绍其它核心组建时提到过很多次的Bootstrap阶段了,在让请求通过中间件和路由之前有一个启动应用程序的过程:

//Class: \Illuminate\Foundation\Http\Kernelprotected function sendRequestThroughRouter($request)
{$this->app->instance('request', $request);Facade::clearResolvedInstance('request');$this->bootstrap();return (new Pipeline($this->app))->send($request)->through($this->app->shouldSkipMiddleware() ? [] : $this->middleware)->then($this->dispatchToRouter());
}//引导启动Laravel应用程序
public function bootstrap()
{if (! $this->app->hasBeenBootstrapped()) {/**依次执行$bootstrappers中每一个bootstrapper的bootstrap()函数$bootstrappers = ['Illuminate\Foundation\Bootstrap\DetectEnvironment','Illuminate\Foundation\Bootstrap\LoadConfiguration','Illuminate\Foundation\Bootstrap\ConfigureLogging','Illuminate\Foundation\Bootstrap\HandleExceptions','Illuminate\Foundation\Bootstrap\RegisterFacades','Illuminate\Foundation\Bootstrap\RegisterProviders','Illuminate\Foundation\Bootstrap\BootProviders',];*/$this->app->bootstrapWith($this->bootstrappers());}
}

在启动应用的过程中Illuminate\Foundation\Bootstrap\RegisterFacades这个阶段会注册应用程序里用到的Facades。

class RegisterFacades
{/*** Bootstrap the given application.** @param  \Illuminate\Contracts\Foundation\Application  $app* @return void*/public function bootstrap(Application $app){Facade::clearResolvedInstances();Facade::setFacadeApplication($app);AliasLoader::getInstance(array_merge($app->make('config')->get('app.aliases', []),$app->make(PackageManifest::class)->aliases()))->register();}
}

在这里会通过AliasLoader类的实例将为所有Facades注册别名,Facades和别名的对应关系存放在config/app.php文件的$aliases数组中

'aliases' => ['App' => Illuminate\Support\Facades\App::class,'Artisan' => Illuminate\Support\Facades\Artisan::class,'Auth' => Illuminate\Support\Facades\Auth::class,......'Route' => Illuminate\Support\Facades\Route::class,......
]

看一下AliasLoader里是如何注册这些别名的

// class: Illuminate\Foundation\AliasLoader
public static function getInstance(array $aliases = [])
{if (is_null(static::$instance)) {return static::$instance = new static($aliases);}$aliases = array_merge(static::$instance->getAliases(), $aliases);static::$instance->setAliases($aliases);return static::$instance;
}public function register()
{if (! $this->registered) {$this->prependToLoaderStack();$this->registered = true;}
}protected function prependToLoaderStack()
{// 把AliasLoader::load()放入自动加载函数队列中,并置于队列头部spl_autoload_register([$this, 'load'], true, true);
}

通过上面的代码段可以看到AliasLoader将load方法注册到了SPL __autoload函数队列的头部。看一下load方法的源码:

public function load($alias)
{if (isset($this->aliases[$alias])) {return class_alias($this->aliases[$alias], $alias);}
}

在load方法里$aliases配置里的Facade类创建了对应的别名,比如当我们使用别名类Route时PHP会通过AliasLoader的load方法为把Illuminate\Support\Facades\Route::class类创建一个别名类Route,所以我们在程序里使用别Route其实使用的就是`Illuminate\Support\Facades\Route类。

解析Facade代理的服务

把Facades注册到框架后我们在应用程序里就能使用其中的Facade了,比如注册路由时我们经常用Route::get('/uri', 'Controller@action);,那么Route是怎么代理到路由服务的呢,这就涉及到在Facade里服务的隐式解析了, 我们看一下Route类的源码:

class Route extends Facade
{/*** Get the registered name of the component.** @return string*/protected static function getFacadeAccessor(){return 'router';}
}

只有简单的一个方法,并没有get, post, delete等那些路由方法, 父类里也没有,不过我们知道调用类不存在的静态方法时会触发PHP的__callStatic静态方法

public static function __callStatic($method, $args)
{$instance = static::getFacadeRoot();if (! $instance) {throw new RuntimeException('A facade root has not been set.');}return $instance->$method(...$args);
}//获取Facade根对象
public static function getFacadeRoot()
{return static::resolveFacadeInstance(static::getFacadeAccessor());
}/*** 从服务容器里解析出Facade对应的服务*/
protected static function resolveFacadeInstance($name)
{if (is_object($name)) {return $name;}if (isset(static::$resolvedInstance[$name])) {return static::$resolvedInstance[$name];}return static::$resolvedInstance[$name] = static::$app[$name];
}

通过在子类Route Facade里设置的accessor(字符串router), 从服务容器中解析出对应的服务,router服务是在应用程序初始化时的registerBaseServiceProviders阶段(具体可以看Application的构造方法)被\Illuminate\Routing\RoutingServiceProvider注册到服务容器里的:

class RoutingServiceProvider extends ServiceProvider
{/*** Register the service provider.** @return void*/public function register(){$this->registerRouter();......}/*** Register the router instance.** @return void*/protected function registerRouter(){$this->app->singleton('router', function ($app) {return new Router($app['events'], $app);});}......
}

router服务对应的类就是\Illuminate\Routing\Router, 所以Route Facade实际上代理的就是这个类,Route::get实际上调用的是\Illuminate\Routing\Router对象的get方法

/*** Register a new GET route with the router.** @param  string  $uri* @param  \Closure|array|string|null  $action* @return \Illuminate\Routing\Route*/
public function get($uri, $action = null)
{return $this->addRoute(['GET', 'HEAD'], $uri, $action);
}

补充两点:

  1. 解析服务时用的static::$app是在最开始的RegisterFacades里设置的,它引用的是服务容器。
  2. static::$app['router'];以数组访问的形式能够从服务容器解析出router服务是因为服务容器实现了SPL的ArrayAccess接口, 对这个没有概念的可以看下官方文档ArrayAccess

总结

通过梳理Facade的注册和使用流程我们可以看到Facade和服务提供者(ServiceProvider)是紧密配合的,所以如果以后自己写Laravel自定义服务时除了通过组件的ServiceProvider将服务注册进服务容器,还可以在组件中提供一个Facade让应用程序能够方便的访问你写的自定义服务。

本文已经收录在系列文章Laravel源码学习里,欢迎访问阅读。

Laravel核心解读--Facades相关推荐

  1. Laravel核心解读--服务容器(IocContainer)

    Laravel的核心是IocContainer, 文档中称其为"服务容器",服务容器是一个用于管理类依赖和执行依赖注入的强大工具,Laravel中的功能模块比如 Route.Elo ...

  2. Laravel核心解读--完结篇

    过去一年时间写了20多篇文章来探讨了我认为的Larave框架最核心部分的设计思路.代码实现.通过更新文章自己在软件设计.文字表达方面都有所提高,在刚开始决定写Laravel源码分析地文章的时候我地期望 ...

  3. Laravel核心解读--完结篇 1

    过去一年时间写了20多篇文章来探讨了我认为的Larave框架最核心部分的设计思路.代码实现.通过更新文章自己在软件设计.文字表达方面都有所提高,在刚开始决定写Laravel源码分析地文章的时候我地期望 ...

  4. Laravel核心解读--服务提供器(ServiceProvider)

    服务提供器是所有 Laravel 应用程序引导中心.你的应用程序自定义的服务.第三方资源包提供的服务以及 Laravel 的所有核心服务都是通过服务提供器进行注册(register)和引导(boot) ...

  5. Laravel核心解读--控制器

    控制器 控制器能够将相关的请求处理逻辑组成一个单独的类, 通过前面的路由和中间件两个章节我们多次强调Laravel应用的请求在进入应用后首现会通过Http Kernel里定义的基本中间件 protec ...

  6. Laravel核心解读--Console内核

    Console内核 上一篇文章我们介绍了Laravel的HTTP内核,详细概述了网络请求从进入应用到应用处理完请求返回HTTP响应整个生命周期中HTTP内核是如何调动Laravel各个核心组件来完成任 ...

  7. Laravel核心解读--HTTP内核

    Http Kernel Http Kernel是Laravel中用来串联框架的各个核心组件来网络请求的,简单的说只要是通过public/index.php来启动框架的都会用到Http Kernel,而 ...

  8. Laravel核心解读--Contracts契约

    Contracts Laravel 的契约是一组定义框架提供的核心服务的接口, 例如我们在介绍用户认证的章节中到的用户看守器契约IllumninateContractsAuthGuard 和用户提供器 ...

  9. Laravel核心解读--Cookie源码分析

    Laravel Cookie源码分析 使用Cookie的方法 为了安全起见,Laravel 框架创建的所有 Cookie 都经过加密并使用一个认证码进行签名,这意味着如果客户端修改了它们则需要对其进行 ...

最新文章

  1. 2019 年,10篇新颖到出格的 AI 论文
  2. mxnet 衰减学习率
  3. tableau做折线图_Tableau | 20种常用图表(上文)
  4. 工控机的io开发_Amazing!从树莓派4B主板到嵌入式无风扇工控机,只需三步!
  5. python学习笔记——类
  6. Python3+WebSockets实现WebSocket通信
  7. 苹果7手机计算机怎么看历史记录,苹果手机safari书签及其历史记录怎么恢复
  8. 使用DBI(perl)实现文本文件的导入导出mysql
  9. 富人和穷人的对比图,时刻提醒自己!
  10. 设计模式之行为类模式大PK
  11. 成功销售的六个关键步骤
  12. Nginx使用memcached外置缓存
  13. Android发送edp服务器,Android6.0调试笔记之edp屏无法点亮问题怎么解决
  14. JavaScript进阶-高级特性及ES6
  15. 【UNI-APP】新闻资讯APP总结
  16. 视频播放器(二)——播放列表
  17. 扫雷游戏软件测试,软件测试-扫雷游戏
  18. 关于C++ delete 来释放new分配的内存
  19. 【加法器】数电中,计算机是如何运算加法的?
  20. java地址簿管理系统

热门文章

  1. Kai - Golang实现的目标检测云服务
  2. vagrant打造自己的开发环境~~我也来一发
  3. 静态网站优化技巧总结
  4. 在sphinx中处理使用特殊字符时所引起错误的办法
  5. jqGrid数据增删查改
  6. 需做勿畏拖 效能更轻松
  7. css的工作原理及使用规则
  8. Linux(centOS)手动安装删除Apache+MySQL+PHP+Memcached原创无错版
  9. 网络游戏:为什么失败
  10. SpringCloud config 配置中心介绍与基本配置使用