2010-12-07 26 views
2

为了使用Memcached,我是否必须修改应用程序中的每个查询?如何使用PDO实现Memcached

我使用这个DB类与PDO教程:

class DB { 

private static $host; 
private static $dbName; 
private static $user; 
private static $password; 

/*** Declare instance ***/ 
private static $instance = NULL; 

/** 
* 
* the constructor is set to private so 
* so nobody can create a new instance using new 
* 
*/ 
private function __construct() {} 

/** 
* 
* Return DB instance or create intitial connection 
* @return object (PDO) 
* @access public 
* 
*/ 
public static function getInstance() { 

    if (!self::$instance){ 
     self::$instance = new PDO("mysql:host=".self::$host.";dbname=".self::$dbName, self::$user, self::$password); 
     self::$instance-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    } 
    return self::$instance; 
} 

/** 
* 
* Like the constructor, we make __clone private 
* so nobody can clone the instance 
* 
*/ 
private function __clone(){} 

} /*** end of class ***/ 

是否有修改它纳入Memcached的一个很好的简单的方法?

+0

可能的重复[如何设计使用PDO和memcached的高速缓存系统?](http://stackoverflow.com/questions/2600720/how-i-can-design-a-cache-system-using-pdo-and-memcached) – RobertPitt 2010-12-07 13:53:18

+0

@Robert我读过那个问题及其链接,这些都没有帮助我。 – bcmcfc 2010-12-07 14:33:13

回答

3

首先,我将重新结构类来扩展PDO类像这样:

class Database extends PDO 
{ 
    /** 
    * 
    * the constructor is set to private so 
    * so nobody can create a new instance using new 
    * 
    */ 
    private static $Instance; 
    public $Cache = null; 

    public function Instance() 
    { 
     if(self::$Instance === null) 
     { 
      self::$Instance = new Database; 
      self::$Instance->Cache = new Memcached; 
     } 
     return self::$Instance; 
    } 

    public function __construct() 
    { 
     parent::__construct("Connection;String"); 
     $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('DBStatement', array(&$this))); 
    } 
} 

class DBStatement extends PDOStatement 
{ 
    public $db; 

    protected function __construct(&$db) 
    { 
     $this->db =& $db; 
    } 
    /* 
     * PDO Methods! 
    */ 

    public function rowCount() 
    { 
        return $this->foundRows; 
    } 

     public function execute($array = null) 
    { 
         if ($array === null) 
         { 
             $result = parent::execute(); 
         }else 
     { 
            $result = parent :: execute($array); 
        } 
     return $result; 
    } 
} 

然后方法将被覆盖在上述类DBStatement的例子中,与执行。

每种方法都会返回一组结果,你会为它们查询md5查询来为该查询创建一个唯一的哈希,然后检查它是否存在于缓存中,如果是的话,你会返回,否则只是运行一个新的查询获取结果,然后在返回它们之前,将它们存储在高速缓存中