简单的页面级缓存类
<?php
class AutoCache{
private $_CACHE_ROOT = "d:/cache/"; //缓存路径
private $_CATHE_LIFE = 86400; //生命周期,86400秒为一天
private $_CACHE_SUFFIX = ".html"; //缓存文件扩展名
private $cache_file_name; //缓存文件名
private $cache_path; //当前文件所存储的路径
function __construct(){
//通过md5的前2位命名目录,防止单目录下文件过多
//如页面还是比较庞大,可取md5的3、4位增加一级目录,单目录文件不多于1000
$this->cache_file_name = md5( $_SERVER["REQUEST_URI"] ) . $this->_CACHE_SUFFIX;
$this->cache_path = $this->_CACHE_ROOT . substr( $this->cache_file_name, 0, 2 );
if( "GET" == $_SERVER["REQUEST_METHOD"] ){
if( file_exists( $this->cache_path . "/" . $this->cache_file_name ) && time() - filemtime( $this->cache_path . "/" . $this->cache_file_name ) < $this->_CATHE_LIFE ){
echo file_get_contents( $this->cache_path . "/" . $this->cache_file_name );
exit;
} else {
ob_start( array( &$this, "saveCache" ) );
}
}elseif( file_exists( $this->cache_path . "/" . $this->cache_file_name ) ){
unlink( $this->cache_path . $this->cache_file_name );
}
}
function saveCache( $buffer ){
if( !file_exists( $this->_CACHE_ROOT ) ){
mkdir( $this->_CACHE_ROOT, 0777 );
}
if( !file_exists( $this->cache_path ) ){
mkdir( $this->cache_path, 0777 );
}
file_put_contents( $this->cache_path . "/" . $this->cache_file_name, $buffer, LOCK_EX );
return $buffer;
}
function __destruct(){
chdir( $this->_CACHE_ROOT ) or die( "缓存路径不存在!!" );
foreach ( glob( "*/*" . $this->_CACHE_SUFFIX ) as $file){
if( time() - filemtime( $file ) > $this->_CATHE_LIFE ){
unlink( $file );
}
}
}
}
?>