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 能夠被這樣直接使用因?yàn)槭褂昧?Facade, 效果是通過 Cache 類使用靜態(tài)方法調(diào)用容器中綁定的相應(yīng)的類解析出的實(shí)例的對(duì)應(yīng)方法。

有點(diǎn)繞額。

首先,Cache 實(shí)際是 Illuminate\Support\Facades\Cache 的別名,通過 class_alias 函數(shù)實(shí)現(xiàn)的, 這個(gè)步驟稍后再看。

Illuminate\Support\Facades\Cache 里繼承 Illuminate\Support\Facades\Facade 并且實(shí)現(xiàn)了一個(gè)getFacadeAccessor方法。

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

回到 Cache::get('user:'.$id) 這個(gè)語句,當(dāng)這個(gè)類沒有找到get靜態(tài)方法的時(shí)候,父類里的魔術(shù)方法會(huì)被調(diào)用。

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 方法應(yīng)該是要返回一個(gè)對(duì)象。

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

getFacadeAccessor()方法在子類里定義了,只是返回一個(gè)字符串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會(huì)賦值為容器,也就是 $app['cache'], $app的父類繼承了 ArrayAccess,于是 $app['cache'] 實(shí)際是調(diào)用了 $app->offsetGet('cache'), 實(shí)現(xiàn) $app->make('cache')

在回到最初,Illuminate\Support\Facades\Cache 在哪里把 Cache 設(shè)置為別名,需要過一下 Laravel 的啟動(dòng)過程??聪氯肟谖募?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 的實(shí)例,下一句執(zhí)行App\Http\Kernel 父類 Illuminate\Foundation\Http 中的handle方法,handle方法中調(diào)用了 sendRequestThroughRouter 方法, 這個(gè)方法里又執(zhí)行 bootstrap 方法,這個(gè)方法是把需要啟動(dòng)的類名數(shù)組傳遞給容器的 bootstrapWith 方法來執(zhí)行。

看下數(shù)組

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,就是注冊(cè)Facades應(yīng)該就是要找的類了。那傳入容器 Illuminate\Foundation\Application 中的bootstrapWith 方法會(huì)發(fā)生什么額。

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 的實(shí)例,執(zhí)行里面的 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,也就是別名和對(duì)應(yīng)Facade類。
$app->make('config')返回的是一個(gè) Illuminate\Config\Repository 對(duì)象,這個(gè)設(shè)置是在 bootstrapWith 調(diào)用 Illuminate\Foundation\Bootstrap\LoadConfiguration 的時(shí)候,暫且不說。

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

把這個(gè)數(shù)組傳入 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;
}

就是把a(bǔ)liases賦值給了

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 函數(shù),放到了autoload的處理過程中,這個(gè)不管,看下 load 函數(shù),就是那個(gè)數(shù)組里的Facade類都設(shè)置一個(gè)別名。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 先說幾句廢話,調(diào)和氣氛。事情的起由來自客戶需求頻繁變更,偉大的師傅決定橫刀立馬的改革使用新的框架(created ...
    wsdadan閱讀 3,198評(píng)論 0 12
  • 文章簡單介紹了 Facade 門面,總結(jié)了其工作原理,并介紹了 Facade 的使用方法。 介紹 Facade 為...
    Think_Heart閱讀 802評(píng)論 0 0
  • 本文面向php語言的laravel框架的用戶,介紹一些laravel框架里面容器管理方面的使用要點(diǎn)。文章很長,但是...
    spacexxxx閱讀 1,293評(píng)論 0 1
  • Facade是容器中的類的靜態(tài)代理,可以調(diào)用容器中任何對(duì)象的任何方法。 Route::get(‘/cache’, ...
    chenhongting閱讀 589評(píng)論 0 0
  • Facade 布局是在面向?qū)ο缶幊讨薪?jīng)常使用的一種軟件設(shè)計(jì)布局方式。Facade 實(shí)際上是一種包括復(fù)雜函數(shù)庫的類,...
    OneAPM閱讀 1,571評(píng)論 0 15

友情鏈接更多精彩內(nèi)容