存档

文章标签 ‘PDO’

PDO下的数据缓存

2009年2月24日

原文地址:http://bbs.phpchina.com/viewthread.php?tid=58800&extra=&highlight=pdo&page=1

这是基于文件系统的一个数据缓存, 思路方法还不错, 转载了一下. 缓存和数据耦合这块代码实现还值得商榷

注:源代码我略加修改,以下是改过后的代码

<?php
class MyCacheDB extends PDO {
	private $_cache = array("cacheDir" => "cache", "cacheExpire" => 7200);
 
	// 缓存读取
	public function cquery($sql) {
		if ($this->_cache['cacheDir'] == null
			|| !is_dir($this->_cache['cacheDir']))
			exit('缓存目录不存在');
		else {
			$this->_cache['cacheDir'] = str_replace("\\", "/", $this->_cache['cacheDir']);
			$fileName = trim($this->_cache['cacheDir'], "/").'/'.urlencode(trim($sql)).'.sql';
		}
 
		// 判断缓存
		if (!file_exists($fileName) 
			|| time() - filemtime($fileName) > $this->_cache['cacheExpire']) {
			if ($tmpRS = parent::query($sql)) {
				$data = serialize($tmpRS->fetchAll());
				$this->createFile($fileName, $data);
			}
			else {
				exit('SQL错误');
			}
		}
		return $this->readCache($fileName);
	}
 
	// 读取缓存文件
	private function readCache($fileName) {
		if (is_file($fileName) && $data = file_get_contents($fileName)) {
			return new CachedStatement(unserialize($data));
		}
		return false;
	}
 
	// 生成文件
	private function createFile($fileName, $data = '') {
		if (file_put_contents($fileName, $data))
			return true;
		return false;
	}
 
	public function __set($k, $v) {
		if (array_key_exists($k, $this->_cache))
			$this->_cache[$k] = $v;
		else
			throw new Exception('属性不存在');
	}
 
	public function __get($k) {
		return isset($this->_cache[$k]) ? $this->_cache[$k] : null;
	}
}
 
 
// 缓存
class CachedStatement {
	private $_record = array();
	private $_cursorId = 0;
	private $_recordCnt = 0;
 
	public function __construct($record) {
		$this->_record = $record;
		$this->_recordCnt = count($record);
	}
 
	public function fetch() {
		if ($this->cursorId == $this->_recordCnt)
			return false;
		else if ($this->_cursorId == 0) {
			$this->_cursorId++;
			return current($this->_record);
		}
		else {
			$this->_cursorId++;
			return next($this->_record);
		}
	}
 
	public function fetchAll() {
		return $this->_record;
	}
 
	public function fetchColumn() {
		$tmp = current($this->_record);
		return $tmp[0];
	}
}
 
 
header('content-type:text/html; charset=utf-8');
 
$db = new MyCacheDB('mysql:host=localhost;dbname=test','root','xxx', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'")); 
 
$db->cacheDir = "cache"; //设置缓存目录
$db->cacheExpire = 7200; //设置缓存时间
 
$rs = $db->cquery("select * from news limit 0,10"); //用缓存查询方法cquery代替query
while ($row = $rs->fetch()) {
 echo $row["title"] . "<br />";
}
 
$rs = null;
$db = null;
 
?>

admin PHP ,