I have basically forgotten the naming of design patterns, so I will call what I am describing now on-demand loading.
Requirements:
1. I hope to have a configuration file reading and writing class, which can be extended without modifying the original configuration file reading and writing class;
2. This extension is for example, my original configuration is in txt format, but Now my configuration class is php or xml, etc., or it may be json
3. The calling interface is unified. No matter what type of configuration file, I just call the same file to configure the read and write class, which prevents subsequent code from being difficult maintain.
Then:
1. First of all, what comes to mind is to define an abstract class and continue to inherit it. Through inheritance, there is no need to modify the configuration file reading and writing class;
2. However, I cannot use this configuration file reading class uniformly. , what I call is the class I inherited;
Implementation idea:
Okay, so much nonsense, let me talk about my implementation idea here. In fact, the whole idea is quite simple;
<code>/** * 定义配置文件读写类,所有的配置文件读写调用此类就可以了,统一接口 */ 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) {} } // 其他配置文件读写类。。。</code>
The above I have not tested the code. What I express is just an idea. Of course, based on this idea, it can be designed to be more flexible. You can add an array configuration to define which class to use for different files to read and write, and the time relationship. This The question will be updated when there is time.
The above introduces the PHP on-demand loading method to increase the flexibility of the program, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.