php如何按需加载方式来增加程序的灵活度
16lz
2021-01-22
设计模式的命名啊什么的,我基本上已经忘记得差不多了,我就把我现在表述的这个东西叫做按需加载吧。
需求:
1.我希望有一个配置文件读写类,不需要修改原本这个配置文件读写类就可以实现扩展;
2.这个扩展是比如我原本的配置是txt格式的,但现在我的配置类是php或者是xml等,也可能是json
3.调用接口统一,不管什么类型的配置文件,我调用同样的 一个文件配置读写类就可以了,防止后续的代码很难维护。
那么:
1.首先,想到的是定义一个抽象类,不断的继承,通过继承不用修改这个配置文件读写类;
2.但是,我就不能统一使用这个配置文件读取类了,我调用的是我继承后的这个类;
实现思想:
好了,废话了那么多,我这里就来说一下我的实现思路,其实整个思路还是挺简单的;
/** * 定义配置文件读写类,所有的配置文件读写调用此类就可以了,统一接口 */class Config { // 读 public function read($file,$type = 'txt') { $instance = $this->getInstance($type); $instance->read($file); } // 写 public function write($file,$type = 'txt') { $instance = $this->getInstance($type); $instance->read($file); } // 删 public function delete($file,$type = 'txt') { $instance = $this->getInstance($type); $instance->read($file); } // 获取实际操作对象实例 public function getInstance($type = 'txt') { $class_name = ucfirst($type).'Config'; // 根据文件格式实例化具体的操作类 if(class_exists($class_name)) { $instance = new $class_name; } else { throw new Exception('未定义'.$class_name); } if(is_subclass_of($instance,'BaseConfig') !== 1) { throw new Exception('配置文件读写类必须继承BaseConfig'); } return $instance; }}// 定义一个基础操作接口类,后续的文件读写必须继承这个规范abstract class BaseConfig { abstract protected function read($file) {} abstract protected function write($file) {} abstract protected function delete($file) {}}// Text配置文件读写类TxtConfig extends BaseConfig { public function read($file) {} public function write($file) {} public function delete($file) {}}// 其他配置文件读写类。。。
更多php相关知识,请访问php教程!
更多相关文章
- php中的接口与抽象类及接口与抽象类的区别
- PHP面向对象之接口详解(代码实例)
- PHP自定义函数xmlToArray的实例解析
- PHP中数组规范和自定义集合
- PHP DIY系列之自定义配置和路由
- PHP预定义接口之Iterator用法示例
- php之接口与前端数据交互实现示例代码
- php抽象类和接口之间有什么区别?
- 示例PHP购物车类Cart.class.php定义与用法