專案中常需快取資料庫查詢結果、API 回應、運算結果以提升效能。本文提供一個輕量、零相依、生產可用的 Cache 類別,採用檔案儲存、MD5 檔名避免衝突、支援 TTL 過期、檔案鎖定防併發、遞迴目錄建立與清理。
<?php
class Cache
{
private string $directory = 'data/cache/';
private string $keySalt = 'c_a_sss'; // 檔名雜湊鹽值
public function __construct(string $directory = '', string $keySalt = '')
{
if ($directory) $this->setDirectory($directory);
if ($keySalt) $this->keySalt = $keySalt;
}
public function setDirectory(string $path): void
{
$this->directory = rtrim($path, '/') . '/';
$this->ensureDirectory($this->directory);
}
/**
* 讀取快取
* @param string $key 快取鍵
* @param int $ttl 存活秒數 (預設 60 秒)
* @return mixed|null 快取資料或 null (過期/不存在)
*/
public function get(string $key, int $ttl = 60): mixed
{
$file = $this->getFilePath($key);
if (!is_file($file)) return null;
$data = @file_get_contents($file);
if ($data === false) return null;
$cache = @unserialize($data);
if (!is_array($cache) || !isset($cache['time'], $cache['data'])) return null;
// 檢查過期
if (time() - $cache['time'] > $ttl) {
@unlink($file); // 刪除過期檔案
return null;
}
return $cache['data'];
}
/**
* 寫入快取
* @return bool 成功與否
*/
public function set(string $key, mixed $data): bool
{
$file = $this->getFilePath($key);
$cache = ['data' => $data, 'time' => time()];
$serialized = serialize($cache);
$dir = dirname($file);
$this->ensureDirectory($dir);
// 使用檔案鎖防止併發寫入損壞
$fp = @fopen($file, 'wb');
if (!$fp) return false;
if (flock($fp, LOCK_EX)) {
$bytes = fwrite($fp, $serialized);
flock($fp, LOCK_UN);
fclose($fp);
return $bytes !== false;
}
fclose($fp);
return false;
}
/** 刪除單一快取 */
public function delete(string $key): bool
{
$file = $this->getFilePath($key);
return is_file($file) && @unlink($file);
}
/** 清空所有快取 */
public function clear(): void
{
$this->deleteDirectory($this->directory);
$this->ensureDirectory($this->directory);
}
/** 取得快取檔案路徑 (MD5 雜湊避免特殊字元、過長) */
private function getFilePath(string $key): string
{
$hash = md5($key . $this->keySalt);
return $this->directory . $key . '_' . $hash . '.cache';
}
/** 遞迴建立目錄 */
private function ensureDirectory(string $path): void
{
if (!is_dir($path)) {
$this->ensureDirectory(dirname($path));
if (!@mkdir($path, 0755, true)) {
throw new RuntimeException("無法建立快取目錄: $path");
}
}
}
/** 遞迴刪除目錄內容 */
private function deleteDirectory(string $dir): void
{
if (!is_dir($dir)) return;
$dh = opendir($dir);
while (($file = readdir($dh)) !== false) {
if ($file === '.' || $file === '..') continue;
$full = $dir . '/' . $file;
if (is_dir($full)) {
$this->deleteDirectory($full);
} else {
@unlink($full);
}
}
closedir($dh);
@rmdir($dir);
}
}
<?php
require 'Cache.php';
$cache = new Cache('storage/cache/', 'my_app_salt_2024');
// 讀取快取,若不存在或過期則執行昂貴操作
$cacheKey = 'homepage_stats';
$stats = $cache->get($cacheKey, 300); // 5 分鐘 TTL
if ($stats === null) {
// 模擬昂貴操作 (資料庫查詢、API 呼叫、複雜運算)
$stats = [
'total_users' => 12543,
'today_orders' => 342,
'revenue' => 1284500,
'generated_at' => date('c'),
];
// 寫入快取
$cache->set($cacheKey, $stats);
echo "資料來自資料庫 (已快取)";
} else {
echo "資料來自快取";
}
print_r($stats);
// 手動清除特定快取
// $cache->delete('homepage_stats');
// 清空所有快取 (部署時)
// $cache->clear();
<?php
class TaggedCache extends Cache
{
private string $tagIndexFile;
public function __construct(string $dir, string $salt = '')
{
parent::__construct($dir, $salt);
$this->tagIndexFile = $this->directory . '.tags.index';
}
public function setWithTags(string $key, mixed $data, array $tags): bool
{
$success = $this->set($key, $data);
if (!$success) return false;
// 更新標籤索引
$index = $this->loadTagIndex();
foreach ($tags as $tag) {
$index[$tag][$key] = true;
}
$this->saveTagIndex($index);
return true;
}
public function invalidateByTag(string $tag): int
{
$index = $this->loadTagIndex();
if (!isset($index[$tag])) return 0;
$count = 0;
foreach (array_keys($index[$tag]) as $key) {
if ($this->delete($key)) $count++;
}
unset($index[$tag]);
$this->saveTagIndex($index);
return $count;
}
private function loadTagIndex(): array
{
return is_file($this->tagIndexFile) ? (unserialize(file_get_contents($this->tagIndexFile)) ?? []) : [];
}
private function saveTagIndex(array $index): void
{
file_put_contents($this->tagIndexFile, serialize($index), LOCK_EX);
}
}
<?php
class MultiLevelCache
{
private array $l1 = []; // 進程內記憶體 (APCu/靜態變數)
private Cache $l2; // 檔案/Redis
public function __construct(Cache $l2) { $this->l2 = $l2; }
public function get(string $key, int $ttl = 60): mixed
{
if (isset($this->l1[$key])) return $this->l1[$key];
$val = $this->l2->get($key, $ttl);
if ($val !== null) $this->l1[$key] = $val;
return $val;
}
public function set(string $key, mixed $data): bool
{
$this->l1[$key] = $data;
return $this->l2->set($key, $data);
}
}
| 方案 | 延遲 | 容量 | 分散式 | 持久化 | 適用場景 |
|---|---|---|---|---|---|
| 檔案 (本類別) | 低 (ms) | 磁碟大小 | ❌ | ✅ | 單機、中小型、開發測試 |
| APCu | 極低 (μs) | 記憶體 (MB~GB) | ❌ | ❌ (重啟消失) | 單機熱點資料、OPcache 配合 |
| Redis | 低 (sub-ms) | 記憶體 (GB~TB) | ✅ | 可選 (AOF/RDB) | 分散式、高併發、需原子操作 |
| Memcached | 極低 | 記憶體 | ✅ | ❌ | 簡單 Key-Value、多節點分散 |
| Database | 高 | 磁碟 | ✅ | ✅ | 關聯查詢、事務一致性、已有 DB |