
ThinkPHP6.0 门面
发布日期:2021-05-09 04:16:32
浏览次数:19
分类:博客文章
本文共 2106 字,大约阅读时间需要 7 分钟。
通过以下三步了解学习:
Facade,即门面设计模式,为容器的类提供了一种静态的调用方式;
- 相比较传统的静态方法调用,带了更好的课测试和扩展性;
- 可以为任何的非静态类库定一个 Facade 类;
- 系统已经为大部分核心类库定义了Facade;
- 所以我们可以通过Facade来访问这些系统类;
- 也可以为我们自己的应用类库添加静态代理;
- 系统给内置的常用类库定义了Facade类库;
自己定义
假如我们定义了一个 app\common\Test 类,里面有一个hello动态方法:
namespace app\common;class Test{ public function hello($name) { return 'hello,' . $name; }}
我们使用之前的方法调用,具体如下
$test = new \app\common\Test;echo $test->hello('thinkphp');// 输出 hello,thinkphp
我们给这个类定义一个静态代理类 app\facade\Test,具体如下:
namespace app\facade;use think\Facade;// 这个类名不一定要和Test类一致,但通常为了便于管理,建议保持名称统一// 只要这个类库继承think\Facade;// 就可以使用静态方式调用动态类 app\common\Test的动态方法;class Test extends Facade{ protected static function getFacadeClass() { return 'app\common\Test'; }}
例如上面调用的代码就可以改成如下:
// 无需进行实例化 直接以静态方法方式调用helloecho \app\facade\Test::hello('thinkphp');// 或者use app\facade\Test;Test::hello('thinkphp');
说的直白一点,Facade功能可以让类无需实例化而直接进行静态方式调用。
系统内置
系统给常用类库定义了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\Response think\facade\Response think\Route think\facade\Route think\Session think\facade\Session think\Validate think\facade\Validate think\View think\facade\View 无需进行实例化就可以很方便的进行方法调用:
namespace app\index\controller;use think\facade\Cache;class Index{ public function index() { Cache::set('name','value'); echo Cache::get('name'); }}
在进行依赖注入的时候,请不要使用 Facade 类作为类型约束,而使用原来的动态类。
事实上,依赖注入和使用 Facade 的效果大多数情况下是一样的,都是从容器中获取对象实例。
以下两种的作用一样,但是引用的类库却不一样
// 依赖注入namespace app\index\controller;use think\Request;class Index{ public function index(Request $request) { echo $request->controller(); }}// 门面模式namespace app\index\controller;use think\facade\Request;class Index{ public function index() { echo Request::controller(); }}
发表评论
最新留言
留言是一种美德,欢迎回访!
[***.207.175.100]2025年04月10日 17时36分57秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
HDU - 4109 Instrction Arrangement
2019-03-11
服务器响应json字符串采用拼接的方式响应时要注意的坑!
2019-03-11
一行代码
2019-03-11
Lua websocket长连接
2019-03-11
SQL 分页查询 返回总条数
2019-03-11
重写的特点
2019-03-11
4、用户及文件权限
2019-03-11
富士电机漏洞预警
2019-03-11
WIFI攻击研究一
2019-03-11
【数据库】MySQL导入文件与导出文件
2019-03-11
计算机网络UDP协议和TCP协议
2019-03-11
Qt中的QGridLayout网格布局类下的两种不同的addWidget功能
2019-03-11
Linux运行C语言文件
2019-03-11
C字符串高级
2019-03-11
2010-03-25 函数题
2019-03-11
C语言_动态内存分配练习
2019-03-11
Linux学习_系统进程概念
2019-03-11
七层网络模型(待添加)
2019-03-11
考研复试——KY276 Problem C
2019-03-11
LeetCode62/63/64 不同路径I/II/最小路径和
2019-03-11