Thinkphp6的Facade门面详解 | Guide and Tutorial

silverwq
2022-10-08 / 0 评论 / 235 阅读 / 正在检测是否收录...

概述

门面主要是为了方便调用类方法,可以像调用静态方法的方式调用非静态方法。例如

class Test
{
    public function hello($name)
    {
        return 'hello,' . $name;
    }
}
// 这个类名不一定要和Test类一致,但通常为了便于管理,建议保持名称统一
class Test extends Facade
{
    protected static function getFacadeClass()
    {
      return 'app\common\Test';
    }
}
// 无需进行实例化 直接以静态方法方式调用hello
\app\facade\Test::hello('thinkphp');

核心实现逻辑

主要是利用魔术方法、容器技术实现

class Facade
{
  // 用于配置是否单例模式
   protected static $alwaysNewInstance;

    // 魔术方法
 public static function __callStatic($method, $params)
    {
      // 调用对象的方法
        return call_user_func_array([static::createFacade(), $method], $params);
    }

    // 可以为其它类增加门面功能
    protected static function getFacadeClass()
    {}

    //
    protected static function createFacade(string $class = '', array $args = [], bool $newInstance = false)
    {
      // 默认只需要继承这个类的话,本类就有门面功能
        $class = $class ?: static::class;

        // 可以为其它类设置门面功能
        $facadeClass = static::getFacadeClass();
        if ($facadeClass) {
            $class = $facadeClass;
        }

        // 是否单例模式
        if (static::$alwaysNewInstance) {
            $newInstance = true;
        }

        // 容器单例
        return Container::getInstance()->make($class, $args, $newInstance);
    }
}
0

评论 (0)

取消