php - 如何使用 PDO 实现 Memcached

标签 php memcached pdo

我是否必须修改应用程序中的每个查询才能使用 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/

相关文章:

ruby-on-rails - Rack session key 对于 memcached 来说太长了

mysql - PDO Select 语句 SQL 进入 MySQL 不产生任何数据

php - 具有 2 个条件的词搜索 PHP PDO

php - 在 GoDaddy 服务器上发送电子邮件时出错 : Laravel 5. 1

php - 从开始日期到当前日期的间隔

php - 切换到MySQLi重要吗?

php - Codeigniter 在本地主机上没问题,但在实时服务器上显示 "database.php does not exist",如果我使用 linux cPanel,我如何找到我的数据库?

使用memcached进行Spring缓存

php - 使用 PHP 在 Memcached 中保存从数据库返回的巨大记录

php - 现在在 Ubuntu(Linux) 上设置时显示 MsSql/odbc 驱动程序