以静态缓存为例。
修改 line:11 去掉 path 参数(方便),加上缓存时间参数:
public function cacheData($k,$v = '',$cacheTime = 0){ //文件名 $filename = $this->_dir.$k.'.'.self::EXT; .....
line:25 把缓存时间设置为 11 位的数字,如果不满 11 位,则在时间前面补 0。再把缓存时间和缓存内容进行拼接:
$cacheTime = sprintf('%011d',$cacheTime); //$cacheTime 设置为11位(方便截取),不满11位前面补0//把缓存时间拼接$vreturn file_put_contents($filename,$cacheTime.json_encode($v));
测试一下:
$file = new Cache();$file->cacheData('data','index-data',50);
打开 data.txt:
00000000050"index-data"
再修改读取缓存 line33:
$contents = file_get_contents($filename);$cacheTime = (int)substr($contents,0,11);$val = substr($contents,11);if($cacheTime != 0 && $cacheTime+filemtime($filename) < time()){ //缓存已经失效 unlink($filename); return false;}return json_decode($val,true);
在 list.php 中引入
修改 line:14
$cache = new Cache();$vals = array();if(!$vals = $cache->cacheData('index-data'.$page.'-'.$pageSize)){ //echo 'aaaa';exit(); //测试缓存失效 try{ $connect = DB::getInstance()->connect(); }catch(Exception $e){ return Response::show(403,'数据库连接失败'); } $res = mysql_query($sql,$connect); while($val = mysql_fetch_assoc($res)){ $vals[] = $val; //二维数组 } if($vals){ $cache->cacheData('index-data'.$page.'-'.$pageSize,$vals,50); }
测试页面:
http://127.0.0.17/php/APP/list.php?pageSize=10&page=3
缓存失效时(没有注释echo 'aaaa';exit(); ),页面输出:aaa
list.php
cacheData('index-data'.$page.'-'.$pageSize)){ //echo 'aaaa';exit(); //测试缓存失效 try{ $connect = DB::getInstance()->connect(); }catch(Exception $e){ return Response::show(403,'数据库连接失败'); } $res = mysql_query($sql,$connect); while($val = mysql_fetch_assoc($res)){ $vals[] = $val; //二维数组 } //同时把取出的数据存入缓存 if($vals){ $cache->cacheData('index-data'.$page.'-'.$pageSize,$vals,50); }}//如果缓存存在同时没有失效,使用封装的接口类封装缓存中的数据if($vals){ return Response::show(200,'首页数据获取成功',$vals);}else{ return Response::show(400,'首页数据获取失败',$vals);}
测试 http://127.0.0.17/php/APP/list.php?pageSize=10&page=3 生成 index-data3-10.txt
测试 http://127.0.0.17/php/APP/list.php?pageSize=10 生成 index-data1-10.txt
附:file.php:
1 _dir = dirname(__FILE__).'/files/'; 9 }10 11 public function cacheData($k,$v = '',$cacheTime = 0){ //默认永久不失效12 //文件名13 $filename = $this->_dir.$k.'.'.self::EXT;14 //$v不为‘’:存储缓存或者删除缓存15 if($v !== ''){16 //删除缓存17 if(is_null($v)){18 return @unlink($filename);19 }20 //存储缓存21 $dir = dirname($filename);22 if(!is_dir($dir)){23 mkdir($dir,0777);24 }25 $cacheTime = sprintf('%011d',$cacheTime); //$cacheTime 设置为11位(方便截取),不满11位前面补026 //把缓存时间拼接$v27 return file_put_contents($filename,$cacheTime.json_encode($v));28 }29 //读取缓存30 if(!is_file($filename)){31 return false;32 }33 $contents = file_get_contents($filename);34 $cacheTime = (int)substr($contents,0,11);35 $val = substr($contents,11);36 if($cacheTime != 0 && $cacheTime+filemtime($filename) < time()){ //缓存已经失效37 unlink($filename);38 return false;39 }40 return json_decode($val,true);41 }42 }
参考: