首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 靜態緩存類實現:頁面級緩存、目錄自動創建、靜態文件輸出與清理機制

     編輯:PHP 相關知識

PHP 靜態緩存類實現:頁面級緩存、目錄自動創建、靜態文件輸出與清理機制

針對 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();
?>

進階應用:生成靜態 HTML

<?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 OpcodeAPCu, OPcache, XCache腳本編譯緩存、減少 CPU 開銷
文件級(本類)自定義文件緩存頁面級片段緩存、中小型項目、無內存服務環境

建議:大型項目建議組合使用(Nginx 靜態緩存 + Redis 數據緩存 + OPcache 代碼緩存),本類適合快速原型、中小型 CMS 或無法安裝擴展的虛擬主機環境。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved