// 自定义缓存类
class Cache_Filesystem {
// 缓存写保存
function set ($key, $data, $ttl) {
//打开文件为读/写模式
$h = fopen($this->get_filename($key), ‘a+‘);
if (!$h) throw new Exception("Could not write to cache");
flock($h, LOCK_EX); //写锁定,在完成之前文件关闭不可再写入
fseek($h, 0); // 读到文件头
ftruncate($h, 0); //清空文件内容
// 根据生存周期$ttl写入到期时间
$data = serialize(array(time()+$ttl, $data));
if (fwrite($h, $data) === false) {
throw new Exception(‘Could not write to cache‘);
}
fclose($h);
}
// 读取缓存数据,如果未取出返回失败信息
function get ($key) {
$filename = $this->get_filename($key);
if ( !file_exists( $filename ) ) {
return false;
}
$h = fopen($filename, ‘r‘);
if (!$h) return false;
// 文件读取锁定
flock($h, LOCK_SH);
$data = file_get_contents($filename);
fclose($h);
$data = @unserialize($data);
if ( !$data ) {
// 如果反序列化失败,则彻底删除该文件
unlink($filename);
return false;
}
if (time() > $data[0]) {
// 如果缓存已经过期,则删除文件
unlink($filename);
return false;
}
}
// 清除缓存
function clear ( $key ) {
$filename = $this->get_filename($key);
if (file_exists($filename)) {
return unlink($filename);
} else {
return false;
}
}
// 获取缓存文件
private function get_filename ($key) {
return ‘./cache/‘ . md5($key);
}
}
调用
require ‘./4.3-cache_class.php‘;
// 创建新对象
$cache = new Cache_Filesystem();
function getUsers () {
global $cache;
// 自定义一个缓存key唯一标识
$key = ‘getUsers:selectAll‘;
// 检测数据是否缓存
if ( !$data = $cache->get( $key ) ) {
// 如果没有缓存,则获取新数据
$db_host = ‘localhost‘;
$db_user = ‘root‘;
$db_password = ‘root‘;
$database = ‘ecshop_test‘;
$conn = mysql_connect( $db_host, $db_user, $db_password);
mysql_select_db($database);
//执行sql查询
$result = mysql_query("select * from ecs_users");
$data = array();
// 将获取到的数据放入数组$data中
while ( $row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
// 保存该数据到缓存中,生存周期为10分钟
$cache->set($key, $data, 10);
}
return $data;
}
try {
$users = getUsers();
print_r($users);
$key = ‘getUsers:selectAll‘;
//$cache->clear($key);
} catch (Exception $e) {
print $e->getMessage();
}
原文:http://www.cnblogs.com/chengzhi59/p/7419523.html