一個不錯的PHP緩存類介紹

webphp 12年前發布 | 1K 次閱讀 YouTube

緩存在實際使用當中應用很廣泛,可以減輕對服務器數據庫的訪問,提高運行速度。目前很多CMS內容管理系統中頻繁使用緩存機制來提高系統運行的效率。下面是一個寫得不錯的緩存類,可以參考下緩存的機制與寫法。

cache.php 代碼如下:

<?
/ 用戶需要事先定義的常量: 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  
    $file=_CachePath_."/".$this->cachefile;  
    //讀取Cache文件的內容  
    if (_CacheEnable_) return readfile($file);  
    else return false;  
}  

//生成Cache  
function write($output) 
{  
    //返回當前頁的Cache  
    $file=_CachePath_."/".$this->cachefile;  
    //如果Cache功能開啟  
    if (_CacheEnable_) 
    {  
        //把輸出的內容寫入Cache文件  
        $fp=@fopen($file,'w');  
        if (!@fputs($fp,$output)) {echo "模板Cache寫入失敗";exit;}  
        @fclose($fp);  
        //如果設置了緩存更新間隔時間 _ReCacheTime_  
        if (_ReCacheTime_+0>0) 
        {  
            //更新當前頁Cache的最后更新時間  
            $file=_CachePath_."/".$this->cachefilevar;  
            $fp=@fopen($file,'w');  
            if (!@fwrite($fp,time())) {echo "Cache目錄無法寫入";exit;}  
            @fclose($fp);  
        }  
    }  
}  

}
?></pre>

 

類的使用:

<?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);
}
?> </pre>

 本文由用戶 webphp 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!