Home  >  Article  >  Backend Development  >  PDO supports data caching_PHP tutorial

PDO supports data caching_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:07:16996browse

/**
*Author: Chu Shi
* QQ: 345610000
​*/
class myPDO extends PDO
{
public $cache_Dir = null; //Cache directory
public $cache_expireTime = 7200; //Cache time, default is two hours

//Query with cache
public function cquery($sql)
{
//Cache storage directory
if ($this->cache_Dir == null || !is_dir($this->cache_Dir)) {
exit ("The cache directory is wrong!");
} else {
$this->cache_Dir = str_replace("", "/", $this->cache_Dir);
$FileName = trim($this->cache_Dir, "/") . '/' . urlencode(trim($sql)) . '.sql';
}
//Judge to generate cache
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 syntax error
");
}
}
return $this->readCache($FileName);
}

//Read cache file
private static function readCache($FilePath)
{
if (is_file($FilePath) && $Data = file_get_contents($FilePath)) {
Return new cache_PDOStatement(unserialize($Data));
}
return false;
}

//Generate file
public static function createFile($FilePath, $Data = '')
{
if (file_put_contents($FilePath, $Data)) {
Return true;
} else {
Return false;
}
}
}
//Cache uses Statement class
class cache_PDOStatement
{
private $recordArr = array();
private $cursorId = 0;
private $recordCount = 0;

public function __construct($arr)
{
$this->recordArr = $arr;
$this->recordCount = count($arr);
}

//Return a record, move the pointer down one line
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);
}
}

//Return all results
public function fetchAll()
{
Return $this->recordArr;
}

//Single row and single column query
public function fetchColumn()
{
$tmpArr = current($this->recordArr);
return $tmpArr[0];
}
}

How to use
$db = new myPDO('mysql: host = localhost;dbname=news','newsadmin','123456');

$db->cache_Dir = "cache"; //Set the cache directory
$db->cache_expireTime = 7200; //Set cache time

$rs = $db->cquery("select * from news limit 0,10"); //Use cache query method cquery instead of query
while ($row = $rs->fetch()) {
echo $row["F_title"] . "
";
}

$rs = null;
$db = null;

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/630439.htmlTechArticle/*** Author: Chu Shi * QQ: 345610000*/ class myPDO extends PDO { public $cache_Dir = null; //cache directory public $cache_expireTime = 7200; //Cache time, default two hours //With buffering...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn