《PHP編程:php實現網頁緩存的工具類分享》要點:
本文介紹了PHP編程:php實現網頁緩存的工具類分享,希望對您有用。如果有疑問,可以聯系我們。
PHP實戰php程序在抵抗大流量拜訪的時候動態網站往往都是難以招架,所以要引入緩存機制,一般情況下有兩種類型緩存
PHP實戰一、文件緩存
PHP實戰二、數據查詢結果緩存,使用內存來實現高速緩存
PHP實戰本例主要使用文件緩存.
PHP實戰主要原理使用緩存函數來存儲網頁顯示結果,如果在規定時間里再次調用則可以加載緩存文件.
PHP實戰工具類代碼:
PHP實戰
// 文件緩存類
class Cache {
/**
* $dir : 緩存文件存放目錄
* $lifetime : 緩存文件有效期,單位為秒
* $cacheid : 緩存文件路徑,包含文件名
* $ext : 緩存文件擴展名(可以不用),這里使用是為了查看文件方便
*/
private $dir;
private $lifetime;
private $cacheid;
private $ext;
/**
* 析構函數,檢查緩存目錄是否有效,默認賦值
*/
function __construct($dir = '', $lifetime = 1800) {
if ($this->dir_isvalid ( $dir )) {
$this->dir = $dir;
$this->lifetime = $lifetime;
$this->ext = '.Php';
$this->cacheid = $this->getcacheid ();
}
}
/**
* 檢查緩存是否有效
*/
private function isvalid() {
if (! file_exists ( $this->cacheid ))
return false;
if (! (@$mtime = filemtime ( $this->cacheid )))
return false;
if (mktime () - $mtime > $this->lifetime)
return false;
return true;
}
/**
* 寫入緩存
* $mode == 0 , 以瀏覽器緩存的方式取得頁面內容
* $mode == 1 , 以直接賦值(通過$content參數接收)的方式取得頁面內容
* $mode == 2 , 以本地讀取(fopen ile_get_contents)的方式取得頁面內容(似乎這種方式沒什么必要)
*/
public function write($mode = 0, $content = '') {
switch ($mode) {
case 0 :
$content = ob_get_contents ();
break;
default :
break;
}
ob_end_flush ();
try {
file_put_contents ( $this->cacheid, $content );
} catch ( Exception $e ) {
$this->error ( '寫入緩存失敗!請檢查目錄權限!' );
}
}
/**
* 加載緩存
* exit() 載入緩存后終止原頁面程序的執行,緩存無效則運行原頁面程序生成緩存
* ob_start() 開啟瀏覽器緩存用于在頁面結尾處取得頁面內容
*/
public function load() {
if ($this->isvalid ()) {
// 以下兩種方式,哪種方式好?????
require_once ($this->cacheid);
echo "<!--緩存-->";
// echo file_get_contents($this->cacheid);
exit ();
} else {
ob_start ();
}
}
/**
* 清除緩存
*/
public function clean() {
try {
unlink ( $this->cacheid );
} catch ( Exception $e ) {
$this->error ( '清除緩存文件失敗!請檢查目錄權限!' );
}
}
/**
* 取得緩存文件路徑
*/
private function getcacheid() {
return $this->dir . md5 ( $this->geturl () ) . $this->ext;
}
/**
* 檢查目錄是否存在或是否可創建
*/
private function dir_isvalid($dir) {
if (is_dir ( $dir ))
return true;
try {
mkdir ( $dir, 0777 );
} catch ( Exception $e ) {
$this->error ( '所設定緩存目錄不存在并且創建失敗!請檢查目錄權限!' );
return false;
}
return true;
}
/**
* 取得當前頁面完整url
*/
private function geturl() {
$url = '';
if (isset ( $_SERVER ['REQUEST_URI'] )) {
$url = $_SERVER ['REQUEST_URI'];
} else {
$url = $_SERVER ['Php_SELF'];
$url .= empty ( $_SERVER ['QUERY_STRING'] ) ? '' : '?' . $_SERVER ['QUERY_STRING'];
}
return $url;
}
/**
* 輸出錯誤信息
*/
private function error($str) {
echo '<div style="color:red;">' . $str . '</div>';
}
}
PHP實戰使用辦法:
PHP實戰使用辦法如下:
PHP實戰一部門代碼放在要被緩存邏輯代碼前面:
歡迎參與《PHP編程:php實現網頁緩存的工具類分享》討論,分享您的想法,維易PHP學院為您提供專業教程。
轉載請注明本頁網址:
http://www.snjht.com/jiaocheng/9468.html