PHP简单的缓存类
转载请标明出处: http://blog.csdn.net/mozillafirefox/ 本文来自 CSDN 博客。x
<?php
/*
* 缓存类 cache
* 作 者:多菜鸟
* 联系邮箱: kingerq AT msn DOT com
* 创建时间: 2006-05-05
* 来源: http://blog.csdn.net/kingerq
* 实 例:
includ "cache.php" ;
$cach = new cach 30 ;
$cache->cacheCheck ;
// 缓存内容开始
echo date "Y-m-d H:i:s" ;
// 缓存内容结束
$cache->cach ;
*/
class cach {
// 缓存目录
var $cacheRoot = "./cache/";
0 为不缓存 // 缓存更新时间秒数。
var $cacheLimitTime = 0;
// 缓存文件名
var $cacheFileName = "";
// 缓存扩展名
var $cacheFileExt = "php";
/*
* 构造函数
* int $cacheLimitTim 缓存更新时间
*/
function cach $cacheLimitTim {
if intval $cacheLimitTim
$this->cacheLimitTim = $cacheLimitTime;
$this->cacheFileNam = $this->getCacheFileNam ;
ob_start ;
}
/*
* 检查缓存文件是否在设置更新时间之内
反之则返回失败 * 返回:如果在更新时间之内则返回文件内容。
*/
function cacheCheck {
if file_exist $this->cacheFileNam {
$cTime = $this->getFileCreateTim $this->cacheFileNam ;
if $cTime + $this->cacheLimitTim > time {
echo file_get_cont $this->cacheFileNam ;
ob_end_flush ;
exit;
}
}
return false;
}
/*
* 缓存文件或者输出静态
* string $staticFileNam 静态文件名(含相对路径)
*/
function cach $staticFileNam = "" {
if $this->cacheFileNam {
$cacheCont = ob_get_cont ;
//echo $cacheContent;
ob_end_flush ;
if $staticFileNam {
$cacheCont $this->saveFil $staticFileName.;
}
if $this->cacheLimitTim
$cacheCont $this->saveFil $this->cacheFileName.;
}
}
/*
* 清除缓存文件
* string $fileNam 指定文件名 ( 含函数 ) 或者 all 全部)
* 返回:清除胜利返回 true 反之返回 false
*/
function clearCach $fileNam = "all" {
if $fileNam != "all" {
$fileNam = $this->cacheRoot . strtoupper md5 $fileNam .".".$this->cacheFileExt;
if file_exist $fileNam {
return @unlink $fileNam ;
}els return false;
}
if is_dir $this->cacheRoot {
if $dir = @opendir $this->cacheRoot {
while $file = @readdir $dir {
$check = is_dir $file ;
if !$check
@unlink $this->cacheRoot . $file ;
}
@closedir $dir ;
return true;
}else{
return false;
}
}else{
return false;
}
}
/*
* 根据当前动态文件生成缓存文件名
*/
function getCacheFileNam {
return $this->cacheRoot . strtoupper md5 $_SERVER["REQUEST_URI"] .".".$this->cacheFileExt;
}
/*
* 缓存文件建立时间
* string $fileName 缓存文件名(含相对路径)
文件不存在返回 * 返回:文件生成时间秒数。0
*/
function getFileCreateTim $fileNam {
if ! trim $fileNam return 0;
if file_exist $fileNam {
return intval filemtim $fileNam ;
}els return 0;
}
/*
* 保管文件
* string $fileName 文件名(含相对路径)
* string $text 文件内容
* 返回:胜利返回 ture 失败返回 false
*/
$text function saveFil $fileName.{
if ! $fileNam || ! $text return false;
if $this->makeDir dirnam $fileNam {
"w" if $fp = fopen $fileName.{
$text if @fwrite $fp.{
fclose $fp ;
return true;
}els {
fclose $fp ;
return false;
}
}
}
return false;
}
/*
* 连续建目录
* string $dir 目录字符串
* int $mode 权限数字
* 返回:顺利创建或者全部已建返回 true 其它方式返回 false
*/
$mode = 0777 function makeDir $dir.{
if ! $dir return 0;
"/", $dir = str_replac "//". $dir ;
$mode if ! preg_match "/^/d+$/".{
$mode = 0777;
}
$mdir = "";
$dir as $val foreach explod "/".{
$mdir .= $val."/";
if $val == ".." || $val == "." || trim $val == "" continue;
if ! file_exist $mdir {
$mode if !@mkdir $mdir.{
return false;
}
}
}
return true;
}
}
?>