您好,欢迎来到尚车旅游网。
搜索
您的当前位置:首页php如何按需加载方式来增加程序的灵活度

php如何按需加载方式来增加程序的灵活度

来源:尚车旅游网

设计模式的命名啊什么的,我基本上已经忘记得差不多了,我就把我现在表述的这个东西叫做按需加载吧。

需求:

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教程!

Copyright © 2019- sceh.cn 版权所有 湘ICP备2023017654号-4

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务