暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Laravel 中 Facade实现原理

左手代码 2017-12-16
231

Laravel 的 Facade 是什么?

Facade 其实是一个容器中类的静态代理,他可以让你以静态的方式来调用存放在容器中任何对象的任何方法。举个例子:

  1. use Illuminate\Support\Facades\Cache;


  2. Route::get('/cache', function () {

  3.    return Cache::get('key');

  4. });

实际上,Cache 类并没有一个 get
静态方法,但是却可以被调用,这就是 Facade 的静态代理功能。

如何使用 Facade?

假如我们自定义了一个类并且放入容器中后,该如何以 Facade 的方式来调用呢?很简单:

  1. use Illuminate\Support\Facades\Facade;


  2. class Cache extends Facade

  3. {

  4.    /**

  5.     * 获取组件注册名称

  6.     *

  7.     * @return string

  8.     */

  9.    protected static function getFacadeAccessor() {

  10.        return 'cache';

  11.    }

  12. }

只要定义一个类让他继承自 Illuminate\Support\Facades\Facade
,并且实现一个抽象方法 getFacadeAccessor
即可。这个方法只要返回一个字符串,就是返回服务容器绑定类的别名。其实,通过源码可以知道,对象不一定要放到容器中,可以直接在这里返回也是可以的,下面会说道:

  1. use Illuminate\Support\Facades\Facade;

  2. use Cache;


  3. class Cache extends Facade

  4. {

  5.    /**

  6.     * 获取组件注册名称

  7.     *

  8.     * @return string

  9.     */

  10.    protected static function getFacadeAccessor() {

  11.        return new Cache;

  12.    }

  13. }

如何实现的呢?

我们来看看 Illuminate\Support\Facades\Facade
的源码:

  1. abstract class Facade

  2. {

  3.    /**

  4.     * The application instance being facaded.

  5.     *

  6.     * @var \Illuminate\Contracts\Foundation\Application

  7.     */

  8.    protected static $app;


  9.    /**

  10.     * The resolved object instances.

  11.     *

  12.     * @var array

  13.     */

  14.    protected static $resolvedInstance;


  15.    /**

  16.     * Get the root object behind the facade.

  17.     *

  18.     * @return mixed

  19.     */

  20.    public static function getFacadeRoot()

  21.    {

  22.        return static::resolveFacadeInstance(static::getFacadeAccessor());

  23.    }


  24.    /**

  25.     * Get the registered name of the component.

  26.     *

  27.     * @return string

  28.     *

  29.     * @throws \RuntimeException

  30.     */

  31.    protected static function getFacadeAccessor()

  32.    {

  33.        throw new RuntimeException('Facade does not implement getFacadeAccessor method.');

  34.    }


  35. /**

  36.     * Resolve the facade root instance from the container.

  37.     *

  38.     * @param  string|object  $name

  39.     * @return mixed

  40.     */

  41.    protected static function resolveFacadeInstance($name)

  42.    {

  43.        if (is_object($name)) {

  44.            return $name;

  45.        }


  46.        if (isset(static::$resolvedInstance[$name])) {

  47.            return static::$resolvedInstance[$name];

  48.        }


  49.        return static::$resolvedInstance[$name] = static::$app[$name];

  50.    }


  51.    /**

  52.     * Handle dynamic, static calls to the object.

  53.     *

  54.     * @param  string  $method

  55.     * @param  array   $args

  56.     * @return mixed

  57.     *

  58.     * @throws \RuntimeException

  59.     */

  60.    public static function __callStatic($method, $args)

  61.    {

  62.        $instance = static::getFacadeRoot();


  63.        if (! $instance) {

  64.            throw new RuntimeException('A facade root has not been set.');

  65.        }


  66.        return $instance->$method(...$args);

  67.    }

  68. }

Facade 的代码不止以上这些,我抽出了核心的部分。直接来看看 __callStatic
这个方法:

  1. public static function __callStatic($method, $args)

  2.    {

  3.        $instance = static::getFacadeRoot();     //解析出实例


  4.        if (! $instance) {

  5.            throw new RuntimeException('A facade root has not been set.');

  6.        }


  7.        return $instance->$method(...$args);     //调用方法

  8.    }

这是 PHP 中的一个魔术方法,当以静态的方式调用一个不存在的方法时,该方法会被调用。代码很简单,就是解析实例调用方法。不过这里要注意一个就是这里使用的是 static
关键字而不是 self
关键字,这涉及到一个后期的静态绑定,可以看看文档:http://php.net/manual/zh/language.oop5.late-static-bindings.php

再来看看 getFacadeRoot
的代码,这个方法就是从容器中解析出对象:

  1. public static function getFacadeRoot(){

  2.    return static::resolveFacadeInstance(static::getFacadeAccessor());

  3. }

  1. protected static function getFacadeAccessor(){

  2.     throw new RuntimeException('Facade does not implement getFacadeAccessor method.');

  3. }

  1. protected static function resolveFacadeInstance($name){

  2.    if (is_object($name)) {

  3.        return $name;

  4.     }


  5.    if (isset(static::$resolvedInstance[$name])) {  

  6.        return static::$resolvedInstance[$name];

  7.    }


  8.    return static::$resolvedInstance[$name] = static::$app[$name];

  9. }

其中的 getFacadeAccessor
这个方法必须被重写,否者就会抛出异常。然后在 resolveFacadeInstance
这个方法中会先判断是否是一个对象,如果是的话就直接返回。所以上文说的 getFacadeAccessor
这个方法直接返回一个对象也是可以的,奥秘就在这。

然后会去判断需要解析的对象是否已经解析过了,如果解析过了就直接返回,否则会从容器中去解析再返回,这样不仅仅实现了单例,而且还可以提升性能。

得到对象后,就是直接通过对象来调用方法了:

  1. $instance->$method(...$args);     //调用方法

总结

其实 Laravel 的 Facade 原理不难,但是在研究的过程是可以发现很多文档没有提供的内容的,也能进一步提高我们阅读源码的能力。


文章转载自左手代码,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论