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

PHP 檔案快取類別設計與實作:PHP_kcache 完整程式碼解析

     編輯:PHP 相關知識

自製檔案快取:原理、程式碼與使用範例

將 PHP 變數/陣列序列化為 PHP 程式碼檔案,下次直接 include 載入,利用 OPcache 加速,是簡單高效的快取策略。

核心類別 PHP_kcache

<?php
class PHP_kcache {
    private string $cacheDir;
    private string $extension = '.cache.php';

    public function __construct(string $cacheDir = './cache') {
        $this->cacheDir = rtrim($cacheDir, '/');
        if (!is_dir($this->cacheDir)) mkdir($this->cacheDir, 0755, true);
    }

    public function set(string $name, mixed $value): bool {
        $code = "<?php\n// Cache created at: " . date('Y-m-d H:i:s') . "\n";
        if (is_array($value)) {
            $code .= "\$$name = " . $this->varExport($value) . ";\n";
        } else {
            $code .= "\$$name = " . var_export($value, true) . ";\n";
        }
        $code .= "?>";
        $file = $this->cacheDir . '/' . $name . $this->extension;
        return (bool)file_put_contents($file, $code, LOCK_EX);
    }

    public function get(string $name, mixed &$out = null): bool {
        $file = $this->cacheDir . '/' . $name . $this->extension;
        if (!is_file($file)) return false;
        include $file; // 直接載入變數
        // 此處需根據具體實作取得變數,簡化示範假設變數名同 $name
        // 實際建議使用固定回傳陣列格式
        return true;
    }

    public function has(string $name): bool {
        return is_file($this->cacheDir . '/' . $name . $this->extension);
    }

    public function delete(string $name): bool {
        $file = $this->cacheDir . '/' . $name . $this->extension;
        return is_file($file) && unlink($file);
    }

    // 產生合法 PHP 陣列/變數定義程式碼
    private function varExport(mixed $var): string {
        if (is_array($var)) {
            $items = [];
            foreach ($var as $k => $v) {
                $key = is_int($k) ? $k : var_export($k, true);
                $items[] = "$key => " . $this->varExport($v);
            }
            return "[" . implode(', ', $items) . "]";
        }
        return var_export($var, true);
    }
}
?>

使用範例

<?php
require 'PHP_kcache.php';
$cache = new PHP_kcache(__DIR__ . '/cache');

// 寫入
$config = ['app_name' => 'MyApp', 'debug' => true, 'limits' => [100, 200]];
$cache->set('config', $config);

// 讀取 (簡化版,實際需解析檔案回傳)
if ($cache->has('config')) {
    include $cache->cacheDir . '/config' . $cache->extension;
    // $config 現在可用
    print_r($config);
}

// 過期策略:可在 get 時比對 filemtime() 與 TTL
?>

優化建議

  • 統一回傳格式:快取檔案存 return ['data' => ..., 'expire' => timestamp];,get() 解析後檢查過期。
  • 鎖機制:寫入用 LOCK_EX,讀取可用 flock 共享鎖避免讀到半寫入檔案。
  • 目錄權限:確保 Web 使用者可讀寫快取目錄,生產環境建議放在 /tmp 或專用卷。
  • OPcache 效果:快取檔案為 PHP 程式碼,OPcache 會編譯緩存,二次載入極快。

此類別適合中小型專案快速引入快取,大型系統建議改用 Redis/Memcached 分散式快取。

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