php pdo 缓冲,PDO支持数据缓存_PHP教程

/**

* 作者:初十

* 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语法错误

“);

}

}

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”] . “

“;

}

$rs = null;

$db = null;

www.bkjia.comtrueTechArticle/** * 作者:初十 * QQ:345610000 */ class myPDO extends PDO { public $cache_Dir = null; //缓存目录 public $cache_expireTime = 7200; //缓存时间,默认两小时 //带缓…

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值