当前位置: 首页 > article >正文

【ThinkPHP】ThinkPHP中的门面(Facade)使用

门面为容器中的(动态)类提供了一个静态调用接口,相比于传统的静态方法调用, 带来了更好的可测试性和扩展性,可以为任何的非静态类库定义一个facade类。

系统已经为大部分核心类库定义了Facade,所以可以通过Facade来访问这些系统类,当然也可以为应用类库添加静态代理。

下面是一个示例,假如我们定义了一个app\common\Test类,里面有一个hello动态方法。

<?php
namespace app\common;

class Test
{
    public function hello($name)
    {
        return 'hello,' . $name;
    }
}

调用hello方法的代码应该类似于:

$test = new \app\common\Test;
echo $test->hello('thinkphp'); // 输出 hello,thinkphp

接下来,给这个类定义一个静态代理类app\facade\Test(这个类名不一定要和Test类一致,但通常为了便于管理,建议保持名称统一)。

<?php
namespace app\facade;

use think\Facade;

class Test extends Facade
{
    protected static function getFacadeClass()
    {
    	return 'app\common\Test';
    }
}

只要这个类库继承think\Facade,就可以使用静态方式调用动态类app\common\Test的动态方法,例如上面的代码就可以改成:

// 无需进行实例化 直接以静态方法方式调用hello
echo \app\facade\Test::hello('thinkphp');

核心Facade类库:
(动态)类库 Facade类
think\App :think\facade\App
think\Cache : think\facade\Cache
think\Config :think\facade\Config
think\Cookie: think\facade\Cookie
think\Db :think\facade\Db
think\Env: think\facade\Env
think\Event :think\facade\Event
think\Filesystem :think\facade\Filesystem
think\Lang :think\facade\Lang
think\Log :think\facade\Log
think\Middleware :think\facade\Middleware
think\Request :think\facade\Request
think\Route :think\facade\Route
think\Session: think\facade\Session
think\Validate :think\facade\Validate
think\View :think\facade\View


http://www.kler.cn/a/37715.html

相关文章:

  • 重磅预告丨Fortinet Demo Day系列实战攻防演练来袭!
  • ZooKeeper ZAB
  • VueCli 脚手架使用
  • Spring第二讲:SpringIoC控制反转、依赖注入
  • 考虑设备动作损耗的配电网分布式电压无功优化(Matlab代码实现)
  • 谈谈——互联网生活中的隐私保护
  • HarmonyOS学习路之方舟开发框架—学习ArkTS语言(基本语法 二)
  • Xcode 更新后 Version 14.3.1报错
  • 路径规划算法:基于袋獾优化的路径规划算法- 附代码
  • [桌面运维] 显示器 色准,色域,色深,分辨率,带宽,刷新率的基本概念,图像呈现的基本原理
  • 【算法第二天7.14】移除链表元素,设计链表,反转链表
  • Inkscape扩展脚本入门
  • STL源码刨析_vector
  • Pytorch基本使用—参数初始化
  • Spring Boot使用DataFreezer操作Aerospike
  • 确定Linux虚拟机需要安装哪个架构的应用
  • mongdb安全认证详解
  • Jenkins Pipline使用SonarScanner 检查 VUE、js 项目 中遇到的Bug
  • 渲染流程(上):HTML、CSS和JavaScript,是如何变成页面的?
  • Flutter:EasyLoading(loading加载、消息提示)