萬盛學電腦網

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

PHP 檔案快取類別 XZCache 完整實作:過期判斷、序列化儲存、狀態回傳

類別設計目標

  • 以檔案儲存快取,支援過期時間 (TTL)
  • 回傳狀態碼:0=無快取、1=命中、2=過期
  • 自動序列化/反序列化複雜資料結構
  • 快取目錄可配置

完整類別程式碼

<?php
class XZCache {
    // 預設快取時間 1 小時
    public $cache_time = 3600;
    // 預設快取目錄
    public $cache_dir = './cache';

    public function __construct($cache_dir = null, $cache_time = null) {
        $this->cache_dir = $cache_dir ?? $this->cache_dir;
        $this->cache_time = $cache_time ?? $this->cache_time;
    }

    // 寫入快取
    public function saveCache($key, $value) {
        if (!is_dir($this->cache_dir)) {
            // 嘗試建立目錄
            if (!mkdir($this->cache_dir, 0755, true)) {
                trigger_error("Error: cannot create cache dir {$this->cache_dir}", E_USER_WARNING);
                return 0;
            }
        }

        $cache_file = $this->cache_dir . '/xzcache_' . md5($key);
        $timedif = @(time() - filemtime($cache_file));

        // 快取過期或不存在,重新寫入
        if ($timedif >= $this->cache_time || !file_exists($cache_file)) {
            $serialized = serialize($value);
            if ($fp = @fopen($cache_file, 'w')) {
                fwrite($fp, $serialized, strlen($serialized));
                fclose($fp);
                return 1;
            }
            trigger_error("Error: cannot write cache file $cache_file", E_USER_WARNING);
            return 0;
        }
        return 1; // 未過期,無需寫入
    }

    // 讀取快取
    // @return array ['cached' => 0|1|2, 'value' => mixed]
    public function getCache($key) {
        $cache_file = $this->cache_dir . '/xzcache_' . md5($key);
        $result = ['cached' => 0, 'value' => null];

        if (is_dir($this->cache_dir) && is_file($cache_file)) {
            $timedif = @(time() - filemtime($cache_file));
            if ($timedif >= $this->cache_time) {
                $result['cached'] = 2; // 過期
            } else {
                $result['value'] = @unserialize(file_get_contents($cache_file));
                $result['cached'] = 1; // 命中
            }
        } else {
            $result['cached'] = 0; // 無快取
        }
        return $result;
    }
}

使用範例

$cache = new XZCache('./my_cache', 1800); // 30 分鐘過期

$key = 'global_config';
$value = ['site_name' => 'MySite', 'debug' => false, 'limits' => [10, 20, 30]];

// 寫入
$cache->saveCache($key, $value);

// 讀取
$result = $cache->getCache($key);
var_dump($result);
/*
array(2) {
  'cached' => int(1)
  'value' => array(3) { ... }
}
*/

// 判斷邏輯
switch ($result['cached']) {
    case 1: echo '快取命中,直接使用'; break;
    case 2: echo '快取過期,重新生成'; break;
    case 0: echo '無快取,首次生成'; break;
}

改進方向(生產級)

  1. 鎖機制:寫入時使用 flock(LOCK_EX) 防併發損壞。
  2. 原子寫入:寫入暫存檔 .tmp 再 rename() 覆蓋,避免讀到半寫入資料。
  3. 序列化器可插拔:支援 JSON、igbinary、msgpack。
  4. 標籤/分組清除:實作 clearByTag()。
  5. 分散式:改用 Redis/Memcached 驅動,介面保持一致。
  6. 快取防穿透:空值快取短時間、布隆過濾器。

快取目錄結構範例

./cache/
├── xzcache_a1b2c3d4e5f6...
├── xzcache_f7e8d9c0b1a2...
└── subdir/
    └── xzcache_...
copyright © 萬盛學電腦網 all rights reserved