开发者

How to implement Memcached with PDO

Do I have to modify every single query in my application in order to use Memcached?

I am using this DB class from a PDO tutorial:

class DB {

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

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

/**
*
* the cons开发者_开发技巧tructor 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 ***/

Is there a nice easy way of modifying it to incorporate Memcached?


firstly I would re structure your class to extend the PDO Class like so:

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;
    }
}

Then the the methods would be overridden as the example in the above class DBStatement, with execute.

Each method that returns an a set of results you would them md5 the query to create a unique hash for that query, you would then check to see if it exists in the cache, if so you would return instead, otherwise just run a new query fetching the results, and then before you return them, store them within the cache

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜