综合实例

文件中写数据

简单写法,使用单例

<?php

// singleton & late static 

class fileDb {
    private $_filePath;
    private $_fp;
    protected static $_instance;

    public static function getInstance($filePath) {
        if(!isset(self::$_instance)) {
            self::$_instance = new static($filePath);
        }
        return self::$_instance;
    }

    private function __construct($filePath) {
        $this->_filePath = $filePath;
        $this->_fp = fopen($this->_filePath, 'a+');
    }

    public function __destruct() {
        fclose($this->_fp);
    }

    public function insert(array $row) {
        fputcsv($this->_fp, $row);
    }
}

$fileDb = fileDb::getInstance('./test.txt');
var_dump($fileDb);
$fileDb->insert(array('revin', '[email protected]'));

引入代码复用(Trait)

将单例模式提出来

禁止反序列化,

禁止克隆

引入事件,闭包和回调函数

当除了插入操作还有其他附加操作,引入事件

引入行为机制(装饰模式)

引入行为模式:动态的向一些类加入一些比不存在的功能, 比如DbBehavior,并不存在于fileDb类中,但是我们又可以使用fileDb实例调用DbBehavior中的方法

进一步优化,将行为机制和事件机制结合

自动注册绑定事件回调函数

进一步引入命名空间,自动加载

文件结构

base/Behavior.php

base/Component.php

base/Singleton.php.php

DbBehavior.php

FileDb.php

index.php

进一步优化,使用自动加载机制

使用了自动加载机制,其它文件中的include删掉即可.

Last updated

Was this helpful?