萬盛學電腦網

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

ThinkPHP 檔案快取類別原始碼解析與使用範例

原始碼解析 (ThinkPHP 3 風格)

<?php
class Cache {
    const C_FILE = '/Runtime/';
    private $dir = '';
    const EXT = '.tpl';
    private $filename = '';

    public function __construct($dir = '') {
        $this->dir = $dir;
    }

    // 設定快取
    public function set($key, $data, $expire = 0) {
        $this->filename = dirname(__FILE__) . self::C_FILE . $this->dir . $key . self::EXT;

        // 內容未變更則略過寫入
        if (file_exists($this->filename)) {
            $res = $this->get($key);
            if (md5($res) === md5(json_encode($data))) return true;
        }

        if (!is_dir(dirname($this->filename))) {
            mkdir(dirname($this->filename), 0777, true);
        }

        $fp = fopen($this->filename, 'w+');
        fwrite($fp, json_encode($data));
        fclose($fp);
        return true;
    }

    // 讀取快取
    public function get($key) {
        if (!file_exists($this->filename)) {
            return '快取檔案不存在';
        }
        return file_get_contents($this->filename);
    }

    // 刪除快取
    public function del($key) {
        return @unlink($this->filename);
    }
}

// 使用範例
$data = ['name' => 'song', 'age' => 20, 'sex' => 'man', 'favority' => ['apple', 'banana']];
$cache = new Cache();
$cache->set('cache', $data);
var_dump($cache->get('cache'));
// $cache->del('cache');

關鍵設計點

  • 以 JSON 序列化儲存,跨語言可讀、支援陣列/物件。
  • MD5 比對避免重複寫入(減少 I/O)。
  • 自動建立多層目錄 (mkdir(..., true))。
  • 固定副檔名 .tpl,統一管理。

ThinkPHP 5/6 現代快取用法

// 設定
Cache::set('key', $data, 3600); // 秒數過期
Cache::set('key', $data, ['expire' => 3600, 'tag' => 'user']);

// 讀取
$value = Cache::get('key');
$value = Cache::get('key', 'default'); // 不存在回傳預設值

// 刪除
Cache::delete('key');
Cache::tag('user')->clear(); // 按標籤清除

// 記憶體快取 (Redis/Memcached 驅動)
// config/cache.php 設定 store => 'redis'
Cache::store('redis')->set('key', $data);

效能優化建議

  • 高頻熱點資料改用 Redis/Memcached(網路 I/O < 磁碟 I/O)。
  • 大型陣列考慮 igbinary 序列化(更快、更小)。
  • 快取穿透/擊穿/雪崩對策:互斥鎖重建、隨機過期時間、多級快取。
  • 部署時清理舊快取:php think clear 或刪除 Runtime/Cache/。
copyright © 萬盛學電腦網 all rights reserved