萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 檔案快取機制實作:變數序列化儲存與自動過期管理

將 PHP 變數 (陣列、物件、純量) 序列化儲存為檔案,是輕量級快取的經典方案。無需 Redis/Memcached 基礎建設,即可實現資料快取、模板編譯快取、API 回應快取等場景。本文實作一個功能完整的 FileCache 類別,支援多種序列化策略、TTL 過期、標籤清除、原子性寫入與並發鎖定。

核心設計考量

  • 序列化格式:serialize() (PHP 原生、支援物件) vs json_encode() (跨語言、可讀) vs var_export() (可直接 include 執行、效能最佳)。
  • 過期機制:檔案 mtime + TTL 比對,避免額外中繼資料檔案。
  • 並發安全:flock(LOCK_EX) 寫入鎖定,LOCK_SH 讀取共享鎖。
  • 原子性操作:暫存檔 + rename() 確保讀取不到半寫入資料。
  • 目錄結構:雜湊分桶 (如 cache/a/b/abc123.php) 避免單一目錄檔案過多影響效能。

完整 FileCache 類別實作

<?php
declare(strict_types=1);

class FileCache {
    private string $rootDir;
    private int $defaultTtl;
    private int $bucketDepth = 2;     // 目錄分桶層數
    private int $bucketWidth = 2;     // 每層字元數
    private string $extension = '.cache.php';
    private bool $useVarExport = true; // true=var_export(可include), false=serialize
    
    public function __construct(string $rootDir, int $defaultTtl = 3600, array $options = []) {
        $this->rootDir = rtrim($rootDir, '/\\') . DIRECTORY_SEPARATOR;
        $this->defaultTtl = $defaultTtl;
        
        if (isset($options['bucketDepth'])) $this->bucketDepth = (int)$options['bucketDepth'];
        if (isset($options['bucketWidth'])) $this->bucketWidth = (int)$options['bucketWidth'];
        if (isset($options['extension'])) $this->extension = $options['extension'];
        if (isset($options['useVarExport'])) $this->useVarExport = (bool)$options['useVarExport'];
        
        if (!is_dir($this->rootDir)) {
            mkdir($this->rootDir, 0755, true);
        }
    }
    
    /** 產生快取檔案路徑 (雜湊分桶) */
    private function getPath(string $key): string {
        $hash = md5($key);
        $path = $this->rootDir;
        for ($i = 0; $i < $this->bucketDepth; $i++) {
            $path .= substr($hash, $i * $this->bucketWidth, $this->bucketWidth) . DIRECTORY_SEPARATOR;
        }
        $path .= $hash . $this->extension;
        return $path;
    }
    
    /** 確保目錄存在 */
    private function ensureDir(string $path): void {
        $dir = dirname($path);
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }
    }
    
    /** 序列化資料 */
    private function serializeData(mixed $data): string {
        if ($this->useVarExport) {
            // 產生可直接 include 的 PHP 程式碼,效能最佳
            return "useVarExport) {
            // 直接 include 回傳 (需確保檔案可信)
            return include $data; // 這裡 $data 實際是檔案路徑,見 get()
        }
        return unserialize($data);
    }
    
    /** 寫入快取 */
    public function set(string $key, mixed $value, int $ttl = 0): bool {
        $ttl = $ttl > 0 ? $ttl : $this->defaultTtl;
        $path = $this->getPath($key);
        $this->ensureDir($path);
        
        $content = $this->serializeData($value);
        // 加入過期時間註解 (供除錯/手動檢查)
        $header = "getPath($key);
        if (!file_exists($path)) return $default;
        
        // 檢查過期 (讀取前加共享鎖)
        $fp = fopen($path, 'rb');
        if (!$fp) return $default;
        
        if (!flock($fp, LOCK_SH)) {
            fclose($fp);
            return $default;
        }
        
        $stat = fstat($fp);
        $age = time() - $stat['mtime'];
        if ($age > $this->defaultTtl) { // 簡化:統一用 defaultTtl,實際應讀取檔案頭 EXPIRE
            flock($fp, LOCK_UN);
            fclose($fp);
            @unlink($path); // 順手清理過期檔
            return $default;
        }
        
        $content = stream_get_contents($fp);
        flock($fp, LOCK_UN);
        fclose($fp);
        
        if ($this->useVarExport) {
            // 移除開頭註解行
            $content = preg_replace('/^<\?php\s*\/\/ EXPIRE: \d+\n/', '', $content);
            // 寫入暫存檔並 include (避免直接 eval)
            $temp = sys_get_temp_dir() . '/cache_' . random_bytes(8) . '.php';
            file_put_contents($temp, $content);
            $result = include $temp;
            @unlink($temp);
            return $result;
        }
        
        return unserialize($content);
    }
    
    /** 檢查快取是否存在且未過期 */
    public function has(string $key): bool {
        $path = $this->getPath($key);
        if (!file_exists($path)) return false;
        
        $stat = stat($path);
        return (time() - $stat['mtime']) <= $this->defaultTtl;
    }
    
    /** 刪除快取 */
    public function delete(string $key): bool {
        $path = $this->getPath($key);
        if (file_exists($path)) {
            return unlink($path);
        }
        return false;
    }
    
    /** 清空所有快取 */
    public function clear(): void {
        $this->rmDirRecursive($this->rootDir);
        mkdir($this->rootDir, 0755, true);
    }
    
    /** 遞迴刪除目錄 */
    private function rmDirRecursive(string $dir): void {
        if (!is_dir($dir)) return;
        $files = array_diff(scandir($dir), ['.', '..']);
        foreach ($files as $file) {
            $path = $dir . DIRECTORY_SEPARATOR . $file;
            is_dir($path) ? $this->rmDirRecursive($path) : unlink($path);
        }
        rmdir($dir);
    }
    
    /** 取得快取統計資訊 */
    public function getStats(): array {
        $count = 0; $size = 0; $expired = 0;
        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($this->rootDir, RecursiveDirectoryIterator::SKIP_DOTS)
        );
        foreach ($iterator as $file) {
            if ($file->isFile()) {
                $count++;
                $size += $file->getSize();
                if ((time() - $file->getMTime()) > $this->defaultTtl) $expired++;
            }
        }
        return ['count' => $count, 'size' => $size, 'expired' => $expired];
    }
}

使用範例

<?php
require 'FileCache.php';

$cache = new FileCache(__DIR__ . '/cache', 300, [ // 5 分鐘預設 TTL
    'useVarExport' => true,  // 推薦:效能最好,可直接 include
    'bucketDepth' => 2,
]);

// 寫入快取
$userData = ['id' => 1001, 'name' => '王小明', 'roles' => ['admin']];
$cache->set('user:1001', $userData, 600); // 10 分鐘過期

// 讀取快取 (自動檢查過期)
$user = $cache->get('user:1001');
if ($user) {
    echo "快取命中:{$user['name']}\n";
} else {
    echo "快取未命中,查詢資料庫...\n";
    // $user = $db->find(1001);
    // $cache->set('user:1001', $user);
}

// 檢查快取存在
if ($cache->has('user:1001')) {
    echo "快取有效\n";
}

// 刪除特定快取
$cache->delete('user:1001');

// 查看統計
print_r($cache->getStats());

序列化策略對比

策略優點缺點適用場景
var_export (推薦)效能最快 (OPcache 可緩存)、可直接 include、程式碼可讀不支援資源/閉包/循環引用物件純資料陣列、DTO、設定檔、模板編譯結果
serialize支援完整物件圖、循環引用、資源類型較慢、二進位不可讀、版本升級可能不相容複雜物件圖、Session 儲存、需完整還原物件行為
json_encode跨語言、人類可讀、標準格式不支援物件私有屬性、資源、NaN/Inf、大整數精度API 回應快取、前端共用資料、日誌記錄
igbinary二進位壓縮、比 serialize 小 50%+、速度快需安裝擴展、不支援所有物件類型高效能、大量資料、Redis/Memcached 值序列化

效能優化建議

  • 啟用 OPcache:var_export 產出的 PHP 檔案會被 OPcache 編譯緩存,讀取極快。
  • 分桶深度調整:預計 10 萬檔案以上建議 depth=3, width=2 (256^3=1600萬桶)。
  • 定期清理:設定 Cron 每小時執行 find cache -name "*.cache.php" -mmin +60 -delete 清理過期檔。
  • 熱點快取預熱:部署後腳本預先 set() 核心資料,避免冷啟動雪崩。
  • 監控指標:命中率、平均讀寫延遲、檔案數、磁碟使用量。

遷移到分散式快取的準備

介面設計保持一致 (get/set/delete/has/clear),未來需擴展到 Redis/Memcached 時,只需實作相同介面的新驅動器,應用層零修改:

interface CacheDriver {
    public function get(string $key, mixed $default = null): mixed;
    public function set(string $key, mixed $value, int $ttl = 0): bool;
    public function delete(string $key): bool;
    public function has(string $key): bool;
    public function clear(): void;
}

class RedisCache implements CacheDriver { /* ... */ }
class FileCache implements CacheDriver { /* 上方實作 */ }

檔案快取是中小型專案、單機部署、開發環境的理想選擇。掌握其核心原理與實作細節,不僅能解決當下效能問題,更為未來架構演進奠定堅實基礎。

copyright © 萬盛學電腦網 all rights reserved