Laravel Facades

Facades,假象,它在laravel中提供了一种快捷操作,你经常使用的`Cookie::get()`或者`Config::get()`等便捷的静态方法就是通过Facades实现的。

Facades

Facades,假象,它在laravel中提供了一种快捷操作,你经常使用的Cookie::get()或者Config::get()等便捷的静态方法就是通过Facades实现的。

举个例子,下面是Facades里的Cookie类的定义。

<?php

namespace Illuminate\Support\Facades;

/**
 * @see \Illuminate\Cookie\CookieJar
 */
class Cookie extends Facade
{
    /**
     * Determine if a cookie exists on the request.
     *
     * @param  string  $key
     * @return bool
     */
    public static function has($key)
    {
        return ! is_null(static::$app['request']->cookie($key, null));
    }

    /**
     * Retrieve a cookie from the request.
     *
     * @param  string  $key
     * @param  mixed   $default
     * @return string
     */
    public static function get($key = null, $default = null)
    {
        return static::$app['request']->cookie($key, $default);
    }

    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return 'cookie';
    }
}

Facade类中的静态方法getFacadeAccessor()返回的就是你在把类的实例绑定到容器的时候给类取的别名,然后你就可以使用你自己的Facade的静态方法来调用你绑定类的动态方法了。那么这种转换是怎么实现的呢,先来介绍一下php类的2个魔术方法_call & _callStaic。

魔术方法_call & _callStaic

PHP 5.3 后新增了__call 与__callStatic 魔法方法。

  • __call当要调用的方法不存在或权限不足时,会自动调用__call方法。
  • __callStatic当调用的静态方法不存在或权限不足时,会自动调用__callStatic方法。
__call($funcname, $arguments)
__callStatic($funcname, $arguments)

其中$funcname为方法的名称,$arguments是方法参数的数组。

其实在Laravel中Facade类就是利用了__callStatic这个魔术方法来延迟调用容器中的对象的方法,实现了将对它调用的静态方法映射到绑定类的动态方法上,这样你就可以使用简单类名调用而不需要记住长长的类名。

在config\app.php中的aliases字段就存放了laravel应用启动时注册的Facades。