如何使用PDO实现Memcached

时间:2010-12-07 13:43:50

标签: php memcached pdo

我是否必须修改应用程序中的每个查询才能使用Memcached?

我在PDO教程中使用这个DB类:

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?

1 个答案:

答案 0 :(得分: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查询为该查询创建一个唯一的哈希,然后你会检查它是否存在于缓存中,如果是这样你会返回,否则只是运行获取结果的新查询,然后在返回结果之前,将它们存储在缓存中