PHP的三个设计模式结合

单例模式

class Db{
    protected static $db;
    private static $_connect = null;
    private $dbConfig = [
        'dsn'=>'mysql:dbname=test;host=127.0.0.1',
        'port'=>'3306',
        'user'=>'root',
        'pwd'=>'root'
    ];
    private function __construct()
    {
        if(!isset(self::$_connect)){
            try {
                self::$_connect = new PDO(
                    $this->dbConfig['dsn'], 
                    $this->dbConfig['user'], 
                    $this->dbConfig['pwd']
                );
                self::$_connect->setAttribute(
                    PDO::ATTR_ERRMODE,
                    PDO::ERRMODE_EXCEPTION
                );
            } catch (PDOException $e) {
                echo 'Connection failed: ' . $e->getMessage();
            }
        }
    }
    private function __clone(){}
    static public function GetInstance()
    {
        if(!(self::$db instanceof self)){
            self::$db = new self();
        }
        return self::$db;
    }
    public function Close()
    {
        self::$_connect = null;
    }
    public function Query($sql)
    {
        return  self::$_connect->query($sql); 
    }
}

首先建好单例模式的DB类,至于什么叫单例模式,就劳烦看官移步去这个博客了解下!

简单工厂模式

class Factory{
    static public function create()
    {
        $db = Db::GetInstance();
        Register::set('db',$db);
    }
}

简单工厂模式就没什么好说的了吧?

注册树模式

class Register{
    protected static $obj=null;
    static public function set($alias,$object)
    {
        self::$obj[$alias] = $object;
    }
    static public function get($name)
    {
        return self::$obj[$name];
    }
    static public function _unset($alias)
    {
        unset(self::$obj[$alias]);
    }
}

建好这三个类,那么我们的业务逻辑代码只需要在注册树上把这个对象读取出来即可!方便实用!

调用实例

Factory::create();
$db = Register::get("db");
$result = $db->Query("select * from esp");
while($row = $result -> fetch()){ 
    print_r($row); 
}

如果路过的大神看到,有什么想法的,可以留言喔~

你可能感兴趣的:(php,设计模式,pdo操作类,php)