
代碼
<?
/*
使用者需要事先定義的常量:
_CachePath_ 模闆緩存路徑
_CacheEnable_ 自動緩存機制是否開啟,未定義或為空,表示關閉自動緩存機制
_ReCacheTime_ 自動重新緩存間隔時間,機關為秒,未定義或為空,表示關閉自動重新緩存
*/
class cache {
var $cachefile;
var $cachefilevar;
function cache() {
//生成目前頁的Cache組檔案名 $this->cachefilevar 及檔案名 $this->cachefile
//動态頁的參數不同對應的Cache檔案也不同,但是每一個動态頁的所有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);
//傳回目前頁的所有Cache檔案組
while (false !== ($entry = $d->read())) {
if (substr($entry,0,$strlen)==$this->cachefilevar) {
if (!unlink(_CachePath_."/".$entry)) {echo "Cache目錄無法寫入";exit;}
}
//判斷是否已Cache過,以及是否需要Cache
function check() {
//如果設定了緩存更新間隔時間 _ReCacheTime_
if (_ReCacheTime_+0>0) {
//傳回目前頁Cache的最後更新時間
$var=@file(_CachePath_."/".$this->cachefilevar);$var=$var[0];
//如果更新時間超出更新間隔時間則删除Cache檔案
if (time()-$var>_ReCacheTime_) {
$this->delete();$ischage=true;
//傳回目前頁的Cache
$file=_CachePath_."/".$this->cachefile;
//判斷目前頁Cache是否存在 且 Cache功能是否開啟
return (file_exists($file) and _CacheEnable_ and !$ischange);
//讀取Cache
function read() {
//傳回目前頁的Cache
//讀取Cache檔案的内容
if (_CacheEnable_) return readfile($file);
else return false;
//生成Cache
function write($output) {
//如果Cache功能開啟
if (_CacheEnable_) {
//把輸出的内容寫入Cache檔案
$fp=@fopen($file,'w');
if (!@fputs($fp,$output)) {echo "模闆Cache寫入失敗";exit;}
@fclose($fp);
if (_ReCacheTime_+0>0) {
//更新目前頁Cache的最後更新時間
$file=_CachePath_."/".$this->cachefilevar;
if (!@fwrite($fp,time())) {echo "Cache目錄無法寫入";exit;}
}
?>
調用方法

<?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);
?>