class Cache {
private $cacheDir; // 缓存目录
private $expire; // 缓存过期时间(秒)
$this->cacheDir = $cacheDir;
$this->expire = $expire;
}
public function get($key) {
$file = md5($key);
$path = $this->cacheDir . '/' . $file;
if (file_exists($path) && time() < filemtime($path) + $this->expire) {
return file_get_contents($path);
}
return null;
}
public function set($key, $content) {
$file = md5($key);
$path = $this->cacheDir . '/' . $file;
file_put_contents($path, $content);
}
public function delete($key) {
$file = md5($key);
$path = $this->cacheDir . '/' . $file;
if (file_exists($path)) {
unlink($path);
}
}
public function clear() {
$files = glob($this->cacheDir . '/*');
foreach ($files as $file) {
if (is_file($file)) {
unlink($file);
}
}
}
}
// 使用示例
$cacheDir = '/path/to/cache'; // 缓存目录
$expire = 3600; // 缓存有效期(秒)
$cache = new Cache($cacheDir, $expire);
$content = $cache->get($key);
if ($content === null) {
// 从数据库或其他数据源获取数据
$data = getDataFromDB();
// 将数据缓存
$cache->set($key, json_encode($data));
$content = json_encode($data);
}
echo $content;