緩存是降低資料庫壓力、提升 API 響應速度的關鍵。本文從零構建一個支援「建立、讀取、刪除」三大操作的檔案緩存類,採用 JSON 序列化儲存陣列資料,目錄自動建立,適用於中小型專案快速落地。
$key 為檔名,$value 經 json_encode 存儲$value 為非空字串/陣列 → 寫入;'' → 讀取;null → 刪除.txt 後綴,便於識別與清理File.php)<?php
class File {
private $_dir;
const EXT = '.txt';
public function __construct() {
$this->_dir = dirname(__FILE__) . '/files/';
}
/**
* 統一入口:建立/讀取/刪除緩存
* @param string $key 緩存鍵名
* @param mixed $value 寫入資料;'' 讀取;null 刪除
* @param string $path 子目錄路徑
* @return mixed 寫入返回字節數/布爾,讀取返回陣列/false,刪除返回布爾
*/
public function cacheData($key, $value = '', $path = '') {
$filename = $this->_dir . $path . $key . self::EXT;
// 寫入或刪除模式
if ($value !== '') {
if (is_null($value)) {
return @unlink($filename); // 刪除
}
// 確保目錄存在
$dir = dirname($filename);
if (!is_dir($dir)) {
mkdir($dir, 0777, true);
}
return file_put_contents($filename, json_encode($value)); // 寫入
}
// 讀取模式
if (!is_file($filename)) {
return false;
}
return json_decode(file_get_contents($filename), true);
}
}
testfile.php)<?php
require_once('./File.php');
$data = [
'id' => 1,
'name' => 'david',
'type' => [4, 5, 6]
];
$file = new File();
// 1. 建立緩存
if ($file->cacheData('davidcache', $data)) {
echo "建立成功";
} else {
echo "建立失敗";
}
// 2. 讀取緩存
// $cache = $file->cacheData('davidcache');
// var_dump($cache);
// 3. 刪除緩存
// if ($file->cacheData('davidcache', null)) {
// echo "刪除成功";
// }
File 類,自動定位 ./files/ 為緩存根目錄cacheData('davidcache', $data) → 在 files/davidcache.txt 寫入 JSON 字串cacheData('davidcache')(第二參數預設空字串) → 讀取並 json_decode 返回關聯陣列cacheData('davidcache', null) → 執行 unlink 刪除檔案flock 檔案鎖防止並發寫入損壞資料此輕量級緩存類零依賴、即插即用,為 PHP 服務端快速引入緩存層提供了極佳起點。