我是否必须修改应用程序中的每个查询才能使用 Memcached?
我正在使用 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?
最佳答案
首先,我将重新构造您的类以扩展 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 中的示例,并使用execute。
每个返回一组结果的方法都可以对查询进行 md5 以便为该查询创建唯一的哈希值,然后检查它是否存在于缓存中,如果存在,则返回,否则只需运行一个新的查询获取结果,然后在返回结果之前,将它们存储在缓存中
关于php - 如何使用 PDO 实现 Memcached,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4377234/