在高併發場景下,資料庫查詢、Web Service 呼叫等 I/O 操作往往成為效能瓶頸。雖然 APC、Zend Optimizer 等擴展能顯著提升效能,但虛擬主機環境常無法安裝。此時,自行實現 PHP 檔案級緩存類成為實用方案。
<?php
class Cache {
protected $options = [];
protected $cacheCount = 0;
protected $cacheTime = 60;
protected $cachePath = 'cache/';
protected $returnType = 1; // 1=陣列, 2=物件
public function readCache($id, $time = 0, $path = '') {
$id = md5($id);
$this->cachePath = empty($path) ? $this->cachePath : $path;
$this->cacheTime = empty($time) ? $this->cacheTime : $time;
$file = $this->cachePath . $id . '.php';
if (file_exists($file)) {
// 檢查過期
if ((filemtime($file) + $this->cacheTime) < time()) {
@unlink($file);
return null;
}
if ($this->returnType === 1) {
return include $file;
} else {
$data = file_get_contents($file);
return unserialize($data);
}
}
return null;
}
public function writeCache($id, $data, $path = '') {
$this->cacheCount++;
$id = md5($id);
$this->cachePath = empty($path) ? $this->cachePath : $path;
$file = $this->cachePath . $id . '.php';
@chmod($this->cachePath, 0777);
if ($this->returnType === 1) {
$data = '<?php return ' . var_export($data, true) . '; ?>';
} else {
$data = serialize($data);
}
return file_put_contents($file, $data);
}
public function delCache($id, $path = '') {
$id = md5($id);
$this->cachePath = empty($path) ? $this->cachePath : $path;
$file = $this->cachePath . $id . '.php';
if (file_exists($file)) {
return unlink($file);
}
return null;
}
public function delAllCache($path = '') {
$this->cachePath = empty($path) ? $this->cachePath : $path;
$dir = $this->cachePath;
if (is_dir($dir)) {
$dh = opendir($dir);
while (($file = readdir($dh)) !== false) {
if ($file !== '..' && $file !== '.') {
$fullPath = $dir . '/' . $file;
if (is_dir($fullPath)) {
$this->delAllCache($fullPath);
} else {
@unlink($fullPath);
}
}
}
closedir($dh);
}
return true;
}
}
<?php
include('cache.php');
$data = ['https://example.com', 'https://google.com', 'https://github.com'];
$cache = new Cache();
$id = 'test_links';
// 寫入緩存
$cache->writeCache($id, $data);
// 讀取緩存(120秒有效期)
$cached = $cache->readCache($id, 120);
print_r($cached);
// 刪除特定緩存
$cache->delCache($id);
// 清空所有緩存
$cache->delAllCache();
cache/ 目錄存在且可寫(權限 0777)