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

资源魔 31 0

设计模式的定名啊甚么的,我根本上曾经遗记患上差没有多了,我就把我如今表述的这个货色叫做按需加载吧。

需要:

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开发教程 php开发资料 php开发自学

抱歉,评论功能暂时关闭!