將 PHP 變數/陣列序列化為 PHP 程式碼檔案,下次直接 include 載入,利用 OPcache 加速,是簡單高效的快取策略。
<?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 共享鎖避免讀到半寫入檔案。/tmp 或專用卷。此類別適合中小型專案快速引入快取,大型系統建議改用 Redis/Memcached 分散式快取。