如何理解Laravel门面

栏目: 编程语言 · PHP · 发布时间: 6年前

内容简介:门面模式也叫外观模式,Laravel的门面为服务提供了一个「静态」代理,相比于传统用法,使用时更加灵活,语法更加简明优雅。举个例子,假如我们绑定了一个服务,传统方式会用以下方式调用服务:用门面模式做静态代理:

如何理解 Laravel 门面

门面模式也叫外观模式,Laravel的门面为服务提供了一个「静态」代理,相比于传统用法,使用时更加灵活,语法更加简明优雅。

举个例子,假如我们绑定了一个服务,传统方式会用以下方式调用服务:

class CacheService
{
    public function get()
    {
        return '从缓存中获取数据';
    }
}

// 绑定服务
$container->singleton('cache', function(){
    return new CacheService();
});
// 从容器中获取服务
$cache = $container->make('cache');
$value = $cache->get();
var_dump($value);

用门面模式做静态代理:

$value = Cache::get();
var_dump($value);

Cache 类就是 cache 服务的静态代理,也可以说 Cache 类就是 cache 服务的门面。通过调用静态方法 Cache::get() ,就能直接调用到 cache 服务中的 get 方法。

我们看一下 Cache 是如何实现静态代理的,非常简单:

class Cache
{
    // cache服务实例
    protected static $instance;

    protected static function getFacadeAccessor()
    {
        // 返回服务名
        return 'cache';
    }

    public static function __callStatic($name, $arguments)
    {
        if (is_null(static::$instance)) {
            // 根据服务名从容器中寻找服务
            static::$instance = app(static::getFacadeAccessor());
        }

        // 调用服务方法
        return call_user_func_array([static::$instance, $name], $arguments);
    }
}

以上所述就是小编给大家介绍的《如何理解Laravel门面》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

A Common-Sense Guide to Data Structures and Algorithms

A Common-Sense Guide to Data Structures and Algorithms

Jay Wengrow / Pragmatic Bookshelf / 2017-8-13 / USD 45.95

If you last saw algorithms in a university course or at a job interview, you’re missing out on what they can do for your code. Learn different sorting and searching techniques, and when to use each. F......一起来看看 《A Common-Sense Guide to Data Structures and Algorithms》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具