/**
* 作者:初十
* QQ:345610000
*/
class myPDO extends PDO
{
public $cache_Dir = null; //緩存目錄
public $cache_expireTime = 7200; //緩存時間,默認兩小時
//帶緩存的查詢
public function cquery($sql)
{
//緩存存放總目錄
if ($this->cache_Dir == null || !is_dir($this->cache_Dir)) {
exit ("緩存目錄有誤!");
} else {
$this->cache_Dir = str_replace("\", "/", $this->cache_Dir);
$FileName = trim($this->cache_Dir, "/") . '/' . urlencode(trim($sql)) . '.sql';
}
//判斷生成緩存
if (!file_exists($FileName) || time() - filemtime($FileName) > $this->cache_expireTime) {
if ($tmpRS = parent::query($sql)) {
$data = serialize($tmpRS->fetchAll());
self::createFile($FileName, $data);
} else {
exit ("SQL語法錯誤<br />");
}
}
return $this->readCache($FileName);
}
//讀緩存文件
private static function readCache($FilePath)
{
if (is_file($FilePath) && $Data = file_get_contents($FilePath)) {
return new cache_PDOStatement(unserialize($Data));
}
return false;
}
//生成文件
public static function createFile($FilePath, $Data = '')
{
if (file_put_contents($FilePath, $Data)) {
return true;
} else {
return false;
}
}
}
//緩存用到Statement類
class cache_PDOStatement
{
private $recordArr = array();
private $cursorId = 0;
private $recordCount = 0;
public function __construct($arr)
{
$this->recordArr = $arr;
$this->recordCount = count($arr);
}
//返回一條記錄,指針下移一行
public function fetch()
{
if ($this->cursorId == $this->recordCount) {
return false;
} else if ($this->cursorId == 0) {
$this->cursorId++;
return current($this->recordArr);
} else {
$this->cursorId++;
return next($this->recordArr);
}
}
//返回全部結果
public function fetchAll()
{
return $this->recordArr;
}
//單行單列查詢
public function fetchColumn()
{
$tmpArr = current($this->recordArr);
return $tmpArr[0];
}
}
使用方法
$db = new myPDO('mysql: host = localhost;dbname=news','newsadmin','123456');
$db->cache_Dir = "cache"; //設置緩存目錄
$db->cache_expireTime = 7200; //設置緩存時間
$rs = $db->cquery("select * from news limit 0,10"); //用緩存查詢方法cquery代替query
while ($row = $rs->fetch()) {
echo $row["F_title"] . "<br />";
}
$rs = null;
$db = null;