Laravel Facade

版本5.1

namespace 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, 效果是通过 Cache 类使用静态方法调用容器中绑定的相应的类解析出的实例的对应方法。

有点绕额。

首先,Cache 实际是 Illuminate\Support\Facades\Cache 的别名,通过 class_alias 函数实现的, 这个步骤稍后再看。

Illuminate\Support\Facades\Cache 里继承 Illuminate\Support\Facades\Facade 并且实现了一个getFacadeAccessor方法。

protected static function getFacadeAccessor()
{
    return 'cache';
}

回到 Cache::get('user:'.$id) 这个语句,当这个类没有找到get静态方法的时候,父类里的魔术方法会被调用。

public static function __callStatic($method, $args)
{
    $instance = static::getFacadeRoot();

    if (! $instance) {
        throw new RuntimeException('A facade root has not been set.');
    }

    switch (count($args)) {
        case 0:
            return $instance->$method();

        case 1:
            return $instance->$method($args[0]);

        case 2:
            return $instance->$method($args[0], $args[1]);

        case 3:
            return $instance->$method($args[0], $args[1], $args[2]);

        case 4:
            return $instance->$method($args[0], $args[1], $args[2], $args[3]);

        default:
            return call_user_func_array([$instance, $method], $args);
    }
}

getFacadeRoot 方法应该是要返回一个对象。

public static function getFacadeRoot()
{
    return static::resolveFacadeInstance(static::getFacadeAccessor());
}

getFacadeAccessor()方法在子类里定义了,只是返回一个字符串cache。

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];
}

$app会赋值为容器,也就是 $app['cache'], $app的父类继承了 ArrayAccess,于是 $app['cache'] 实际是调用了 $app->offsetGet('cache'), 实现 $app->make('cache')

在回到最初,Illuminate\Support\Facades\Cache 在哪里把 Cache 设置为别名,需要过一下 Laravel 的启动过程。看下入口文件 public/index.php

require __DIR__.'/../bootstrap/autoload.php';
$app = require_once __DIR__.'/../bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle(
        $request = Illuminate\Http\Request::capture()
);
$response->send();
$kernel->terminate($request, $response);

容器通过make Illuminate\Contracts\Http\Kernel::class 之后,得到是 App\Http\Kernel 的实例,下一句执行App\Http\Kernel 父类 Illuminate\Foundation\Http 中的handle方法,handle方法中调用了 sendRequestThroughRouter 方法, 这个方法里又执行 bootstrap 方法,这个方法是把需要启动的类名数组传递给容器的 bootstrapWith 方法来执行。

看下数组

protected $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',
];

里面的 Illuminate\Foundation\Bootstrap\RegisterFacades,就是注册Facades应该就是要找的类了。那传入容器 Illuminate\Foundation\Application 中的bootstrapWith 方法会发生什么额。

public function bootstrapWith(array $bootstrappers)
{
    $this->hasBeenBootstrapped = true;

    foreach ($bootstrappers as $bootstrapper) {
        $this['events']->fire('bootstrapping: '.$bootstrapper, [$this]);
        $this->make($bootstrapper)->bootstrap($this);
        $this['events']->fire('bootstrapped: '.$bootstrapper, [$this]);
    }
}

$this->make('Illuminate\Foundation\Bootstrap\RegisterFacades')->bootstrap($this);
也就是解析得到 Illuminate\Foundation\Bootstrap\RegisterFacades 的实例,执行里面的 bootstrap 方法。

public function bootstrap(Application $app)
{
    Facade::clearResolvedInstances();
    Facade::setFacadeApplication($app);
    AliasLoader::getInstance($app->make('config')->get('app.aliases'))->register();
}

看 setFacadeApplication($app) ,就是容器传入facade类,赋值给里面的 $app。

$app->make('config')->get('app.aliases') 可以猜到是取 config/app.php 中的aliases,也就是别名和对应Facade类。
$app->make('config')返回的是一个 Illuminate\Config\Repository 对象,这个设置是在 bootstrapWith 调用 Illuminate\Foundation\Bootstrap\LoadConfiguration 的时候,暂且不说。

'aliases' => [
        ...
        'Cache'     => Illuminate\Support\Facades\Cache::class,
        ...
        ]

把这个数组传入 Illuminate\Foundation\AliasLoader 的getInstance方法。

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;
}

就是把aliases赋值给了

public function register()
{
    if (! $this->registered) {
        $this->prependToLoaderStack();
        $this->registered = true;
    }
}

protected function prependToLoaderStack()
{
    spl_autoload_register([$this, 'load'], true, true);
}

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

就是用 spl_autoload_register 把 load 函数,放到了autoload的处理过程中,这个不管,看下 load 函数,就是那个数组里的Facade类都设置一个别名。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,636评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,890评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,680评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,766评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,665评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,045评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,515评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,182评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,334评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,274评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,319评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,002评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,599评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,675评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,917评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,309评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,885评论 2 341

推荐阅读更多精彩内容

  • 先说几句废话,调和气氛。事情的起由来自客户需求频繁变更,伟大的师傅决定横刀立马的改革使用新的框架(created ...
    wsdadan阅读 3,029评论 0 12
  • 文章简单介绍了 Facade 门面,总结了其工作原理,并介绍了 Facade 的使用方法。 介绍 Facade 为...
    Think_Heart阅读 749评论 0 0
  • 本文面向php语言的laravel框架的用户,介绍一些laravel框架里面容器管理方面的使用要点。文章很长,但是...
    spacexxxx阅读 1,133评论 0 1
  • Facade是容器中的类的静态代理,可以调用容器中任何对象的任何方法。 Route::get(‘/cache’, ...
    chenhongting阅读 516评论 0 0
  • Facade 布局是在面向对象编程中经常使用的一种软件设计布局方式。Facade 实际上是一种包括复杂函数库的类,...
    OneAPM阅读 1,458评论 0 15