php文件缓存封装类,设置缓存时间一个小时
时间: 2024-05-24 18:12:24 浏览: 13
<?php
/**
* PHP文件缓存封装类
*/
class FileCache {
private $cache_dir; // 缓存目录
private $cache_time; // 缓存时间
/**
* 构造函数
* @param string $cache_dir 缓存目录
* @param int $cache_time 缓存时间(秒)
*/
public function __construct($cache_dir, $cache_time=3600) {
$this->cache_dir = $cache_dir;
$this->cache_time = $cache_time;
if(!file_exists($this->cache_dir)) {
mkdir($this->cache_dir, 0777, true);
}
}
/**
* 设置缓存
* @param string $key 缓存key
* @param mixed $value 缓存值
*/
public function set($key, $value) {
$cache_file = $this->getCacheFile($key);
$data = array(
'expire' => time() + $this->cache_time,
'value' => $value
);
file_put_contents($cache_file, serialize($data));
}
/**
* 获取缓存
* @param string $key 缓存key
* @return mixed 缓存值
*/
public function get($key) {
$cache_file = $this->getCacheFile($key);
if(!file_exists($cache_file)) {
return false;
}
$data = unserialize(file_get_contents($cache_file));
if(time() > $data['expire']) {
unlink($cache_file);
return false;
}
return $data['value'];
}
/**
* 删除缓存
* @param string $key 缓存key
*/
public function delete($key) {
$cache_file = $this->getCacheFile($key);
if(file_exists($cache_file)) {
unlink($cache_file);
}
}
/**
* 获取缓存文件名
* @param string $key 缓存key
* @return string 缓存文件名
*/
private function getCacheFile($key) {
return $this->cache_dir . '/' . md5($key) . '.cache';
}
}
// 使用示例
$file_cache = new FileCache('cache', 3600);
$file_cache->set('name', '张三');
echo $file_cache->get('name');
$file_cache->delete('name');
?>