> php教程 > php手册 > 본문

PDO支持数据缓存

WBOY
풀어 주다: 2016-06-13 10:09:58
원래의
2282명이 탐색했습니다.

/**
 * 作者:初十
 * 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;

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 추천
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!