门面

门面工作原理

在 Laravel 应用中,门面就是一个为容器中对象提供访问方式的类。该机制原理由 Facade 类实现。Laravel 自带的门面,以及我们创建的自定义门面,都会继承自 IlluminateSupportFacadesFacade 基类。

门面类只需要实现一个方法:getFacadeAccessor。正是 getFacadeAccessor 方法定义了从容器中解析什么,然后 Facade 基类使用魔术方法 __callStatic() 从你的门面中调用解析对象。

<?php

namespace AppHttpControllers;

use Cache;
use AppHttpControllersController;

class UserController extends Controller{
    /**
     * 为指定用户显示属性
     *
     * @param  int  $id
     * @return Response
     */
    public function showProfile($id)
    {
        $user = Cache::get('user:'.$id);

        return view('profile', ['user' => $user]);
    }
}

注意我们在顶部位置引入了 Cache 门面。该门面作为代理访问底层 IlluminateContractsCacheFactory 接口的实现。我们对门面的所有调用都会被传递给 Laravel 缓存服务的底层实例。

原文地址:https://www.cnblogs.com/hanmengya/p/10944396.html