針對 CMS 等高頻讀、低頻寫場景,頁面級文件緩存能大幅降低數據庫壓力並提升響應速度。本類提供緩存有效期檢查、輸出緩衝捕獲、靜態文件生成、目錄遞歸創建、緩存清理等完整功能,代碼輕量無依賴,直接引入即用。
ob_start(),cacheCheck() 檢測緩存文件是否存在且未過期,命中則直接輸出並 exit。caching() 捕獲輸出緩衝內容,按配置寫入緩存文件或/和靜態 HTML 文件。clearCache() 支持單文件刪除或清空整個緩存目錄。REQUEST_URI 生成 MD5 文件名,makeDir() 遞歸創建多級目錄。<?php
class Cache {
public $cacheRoot = "./cache/"; // 緩存目錄
public $cacheLimitTime = 0; // 緩存有效期(秒),0 為不緩存
public $cacheFileName = ""; // 緩存文件路徑
public $cacheFileExt = "php"; // 緩存文件擴展名
public function __construct($cacheLimitTime = 0) {
if (intval($cacheLimitTime)) $this->cacheLimitTime = $cacheLimitTime;
$this->cacheFileName = $this->getCacheFileName();
ob_start();
}
// 檢查緩存是否有效,命中則直接輸出並終止腳本
public function cacheCheck() {
if (file_exists($this->cacheFileName)) {
$cTime = $this->getFileCreateTime($this->cacheFileName);
if ($cTime + $this->cacheLimitTime > time()) {
echo file_get_contents($this->cacheFileName);
ob_end_flush();
exit;
}
}
return false;
}
// 寫入緩存或生成靜態文件
public function caching($staticFileName = "") {
if ($this->cacheFileName) {
$content = ob_get_contents();
ob_end_flush();
if ($staticFileName) {
$this->saveFile($staticFileName, $content);
}
if ($this->cacheLimitTime) {
$this->saveFile($this->cacheFileName, $content);
}
}
}
// 清理緩存:單文件或全部
public function clearCache($fileName = "all") {
if ($fileName !== "all") {
$file = $this->cacheRoot . strtoupper(md5($fileName)) . "." . $this->cacheFileExt;
return file_exists($file) ? @unlink($file) : false;
}
if (!is_dir($this->cacheRoot)) return false;
if ($dir = @opendir($this->cacheRoot)) {
while ($file = @readdir($dir)) {
if (!is_dir($this->cacheRoot . $file)) {
@unlink($this->cacheRoot . $file);
}
}
@closedir($dir);
return true;
}
return false;
}
// 根據當前請求 URI 生成緩存文件名
private function getCacheFileName() {
return $this->cacheRoot . strtoupper(md5($_SERVER["REQUEST_URI"])) . "." . $this->cacheFileExt;
}
// 獲取文件修改時間
private function getFileCreateTime($fileName) {
if (!trim($fileName)) return 0;
return file_exists($fileName) ? intval(filemtime($fileName)) : 0;
}
// 保存文件(自動創建目錄)
private function saveFile($fileName, $text) {
if (!$fileName || !$text) return false;
if ($this->makeDir(dirname($fileName))) {
if ($fp = fopen($fileName, "w")) {
$result = @fwrite($fp, $text);
fclose($fp);
return $result !== false;
}
}
return false;
}
// 遞歸創建目錄
private function makeDir($dir, $mode = "0777") {
if (!$dir) return false;
$dir = str_replace("\\", "/", $dir);
$mdir = "";
foreach (explode("/", $dir) as $val) {
$mdir .= $val . "/";
if ($val == ".." || $val == "." || trim($val) == "") continue;
if (!file_exists($mdir)) {
if (!@mkdir($mdir, $mode)) return false;
}
}
return true;
}
}
?>
<?php
require_once 'Cache.php';
// 緩存 30 秒
$cache = new Cache(30);
// 檢查緩存,命中則直接輸出並 exit
$cache->cacheCheck();
// 業務邏輯:生成動態內容
echo "當前時間:" . date("Y-m-d H:i:s");
// 寫入緩存文件
$cache->caching();
?>
<?php
$cache = new Cache(3600); // 1 小時緩存
$cache->cacheCheck();
// 複雜頁面渲染邏輯...
echo "<h1>文章標題</h1><p>文章內容...</p>";
// 同時生成緩存文件與靜態 HTML 文件
$cache->caching("static/article_123.html");
?>
| 緩存層級 | 典型方案 | 適用場景 |
|---|---|---|
| HTTP 代理/反向代理 | Squid, Varnish, Nginx fastcgi_cache | 全站靜態化、高併發前端緩存 |
| 內存級 | Memcached, Redis | 高頻熱點數據、會話、分佈式鎖 |
| PHP Opcode | APCu, OPcache, XCache | 腳本編譯緩存、減少 CPU 開銷 |
| 文件級(本類) | 自定義文件緩存 | 頁面級片段緩存、中小型項目、無內存服務環境 |
建議:大型項目建議組合使用(Nginx 靜態緩存 + Redis 數據緩存 + OPcache 代碼緩存),本類適合快速原型、中小型 CMS 或無法安裝擴展的虛擬主機環境。