缓存在实际使用当中应用很广泛,可以减轻对服务器数据库的访问,提高运行速度。目前很多CMS内容管理系统中频繁使用缓存机制来提高系统运行的效率。下面是一个写得不错的缓存类,可以参考下缓存的机制与写法。
cache.php 代码如下:
-
<?
-
-
-
-
-
-
-
-
class cache
-
{
-
var $cachefile;
-
var $cachefilevar;
-
-
function cache()
-
{
-
-
-
$s=array(".","/");$r=array("_","");
-
$this->cachefilevar=str_replace($s,$r,$_SERVER["SCRIPT_NAME"])."_".$_GET[_ActionVar_];
-
$this->cachefile=$this->cachefilevar.".".md5($_SERVER["REQUEST_URI"]);
-
}
-
-
-
function delete()
-
{
-
-
$d = dir(_CachePath_);
-
$strlen=strlen($this->cachefilevar);
-
-
while (false !== ($entry = $d->read()))
-
{
-
if (substr($entry,0,$strlen)==$this->cachefilevar)
-
{
-
if (!unlink(_CachePath_."/".$entry)) {echo "Cache目录无法写入";exit;}
-
}
-
}
-
}
-
-
-
function check()
-
{
-
-
if (_ReCacheTime_+0>0)
-
{
-
-
$var=@file(_CachePath_."/".$this->cachefilevar);$var=$var[0];
-
-
if (time()-$var>_ReCacheTime_)
-
{
-
$this->delete();$ischage=true;
-
}
-
}
-
-
$file=_CachePath_."/".$this->cachefile;
-
-
return (file_exists($file) and _CacheEnable_ and !$ischange);
-
}
-
-
-
function read()
-
{
-
-
$file=_CachePath_."/".$this->cachefile;
-
-
if (_CacheEnable_) return readfile($file);
-
else return false;
-
}
-
-
-
function write($output)
-
{
-
-
$file=_CachePath_."/".$this->cachefile;
-
-
if (_CacheEnable_)
-
{
-
-
$fp=@fopen($file,'w');
-
if (!@fputs($fp,$output)) {echo "模板Cache写入失败";exit;}
-
@fclose($fp);
-
-
if (_ReCacheTime_+0>0)
-
{
-
-
$file=_CachePath_."/".$this->cachefilevar;
-
$fp=@fopen($file,'w');
-
if (!@fwrite($fp,time())) {echo "Cache目录无法写入";exit;}
-
@fclose($fp);
-
}
-
}
-
}
-
}
-
?>
类的使用:
-
<?php
-
define("_CachePath_","./cache/");
-
define("_CacheEnable_","1");
-
define("_ReCacheTime_","43200");
-
include('cache.php');
-
$cache=new cache();
-
if ($cache->check())
-
{
-
$template=$cache->read();
-
}
-
else
-
{
-
ob_start();
-
ob_implicit_flush(0);
-
?>
-
页面内容。。。。
-
<?php
-
$template = ob_get_contents();
-
$cache->write($template);
-
}
-
?>
|