首页 >后端开发 >php教程 >PHP一个小巧的缓存类_PHP教程

PHP一个小巧的缓存类_PHP教程

WBOY
WBOY原创
2016-07-13 17:37:52747浏览

功能很简单,就是缓存整个页面,可以设定缓存时间,可以缓存特定的URL,例如:test.php?id=12,当目标文件更新时,如test.php,缓存文件也会更新,即使仍处于缓存期内。

class cache
{
var $cache_dir = ./cache/;//This is the directory where the cache files will be stored;
var $cache_time = 120;//How much time will keep the cache files in seconds.

var $caching = false;
var $file = ;

function cache()
{
//Constructor of the class
$this->file = $this->cache_dir . urlencode( $_SERVER[REQUEST_URI] );
if(file_exists($this->file)) $expired = $this->check_expire();
else $expired = false;
if ( file_exists ( $this->file ) && ( filemtime ( $this->file ) + $this->cache_time ) > time() && !$expired )
{
//Grab the cache:
$handle = fopen( $this->file , "r");
do {
$data = fread($handle, 8192);
if (strlen($data) == 0) {
break;
}
echo $data;
} while (true);
fclose($handle);
exit();
}
else
{
//create cache :
$this->caching = true;
ob_start();
$now = time();
echo " ";
}
}

function close()
{
//You should have this at the end of each page
if ( $this->caching )
{
//You were caching the contents so display them, and write the cache file
$data = ob_get_clean();
echo $data;
$fp = fopen( $this->file , w );
fwrite ( $fp , $data );
fclose ( $fp );
}
}
function check_expire(){
$fp = fopen($this->file,"r");
preg_match("/:([d]+)-/",fread($fp,200),$time);
$modify_time = $time[1];
if($modify_time return true;
}
else{
return false;
}

}
}


用法:

//Example :
$ch = new cache();
echo date("D M j G:i:s T Y");
$ch->close();

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/486516.htmlTechArticle功能很简单,就是缓存整个页面,可以设定缓存时间,可以缓存特定的URL,例如:test.php?id=12,当目标文件更新时,如test.php,缓存文件也会...
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn