PHP 作為一門解釋型腳本語言,每次請求都需要經歷編譯、執行等步驟。隨著流量增長,重複的資料庫查詢、複雜的運算會成為效能瓶頸。緩存的核心目標是將經常讀取、較少變動的資料存放在高速存取介質中,避免重複計算或 I/O 操作,從而大幅降低響應時間並減輕資料庫負載。
PHP 7+ 內建 Zend OPcache,將編譯後的字節碼存放在共享記憶體中,省去每次請求的解析編譯過程。這是效能提升最大的一環,生產環境務必啟用並調整 opcache.memory_consumption、opcache.max_accelerated_files 等參數。
將動態生成的 HTML 寫入靜態檔案,下次請求直接由 Nginx/Apache 靜態服務。適用於內容更新頻率低的頁面(部落格文章、商品詳情)。可結合 ob_start() 捕獲輸出緩衝區內容寫入檔案,或使用框架內建的頁面緩存元件。
透過 Cache-Control、ETag、Last-Modified 等標頭,讓瀏覽器或 CDN 緩存靜態資源與 API 回應,減少伺服器頻寬與運算。
以下程式碼示範基於檔案鎖定的頁面緩存邏輯,確保併發安全:
<?php
class FileCache {
private string $cacheDir;
private int $expireTime = 180; // 秒
public function __construct(string $dir) {
$this->cacheDir = rtrim($dir, '/');
if (!is_dir($this->cacheDir)) {
mkdir($this->cacheDir, 0777, true);
}
}
private function getCachePath(string $key): string {
return $this->cacheDir . '/' . md5($key) . '.cache';
}
public function get(string $key): mixed {
$file = $this->getCachePath($key);
if (!is_file($file)) return false;
if (time() - filemtime($file) > $this->expireTime) {
unlink($file);
return false;
}
$data = file_get_contents($file);
return $data !== false ? unserialize($data) : false;
}
public function set(string $key, mixed $value): bool {
$file = $this->getCachePath($key);
$fp = fopen($file, 'c');
if (!$fp) return false;
if (flock($fp, LOCK_EX)) {
ftruncate($fp, 0);
fwrite($fp, serialize($value));
flock($fp, LOCK_UN);
}
fclose($fp);
return true;
}
public function delete(string $key): bool {
$file = $this->getCachePath($key);
return is_file($file) && unlink($file);
}
}
PHP 緩存不是單一技術,而是分層組合:OPcache 解決編譯開銷、記憶體 KV 存儲加速資料存取、檔案/HTTP 緩存減輕輸出壓力。根據業務場景選擇合適層級,並建立完善的監控(命中率、延遲、記憶體使用)與失效策略,才能發揮最大效能紅利。