php文件缓存类汇总
本文实例讲述了php的文件缓存类。分享给大家供大家参考。具体分析如下:
缓存类是我们开发应用中会常用使用到的功能,下面就来给大家整理几个php文件缓存类了,各个文件缓存类写法不同,但在性能上会有区别,有兴趣测试的朋友可测试一下这些缓存类。
例1
<?php $fzz=newfzz_cache; $fzz->kk=$_SERVER;//写入缓存 //$fzz->set("kk",$_SERVER,10000);//此方法不与类属性想冲突,可以用任意缓存名; print_r($fzz->kk); //读取缓存 //print_r($fzz->get("kk")); //unset($fzz->kk);//删除缓存 //$fzz->_unset("kk"); var_dump(isset($fzz->kk));//判断缓存是否存在 //$fzz->_isset("kk"); //$fzz->clear();//清理过期缓存 //$fzz->clear_all();//清理所有缓存文件 classfzz_cache{ public$limit_time=20000;//缓存过期时间 public$cache_dir="data";//缓存文件保存目录 //写入缓存 function__set($key,$val){ $this->_set($key,$val); } //第三个参数为过期时间 function_set($key,$val,$limit_time=null){ $limit_time=$limit_time?$limit_time:$this->limit_time; $file=$this->cache_dir."/".$key.".cache"; $val=serialize($val); @file_put_contents($file,$val)or$this->error(__line__,"failtowriteinfile"); @chmod($file,0777); @touch($file,time()+$limit_time)or$this->error(__line__,"failtochangetime"); }
//读取缓存 function__get($key){ return$this->_get($key); } function_get($key){ $file=$this->cache_dir."/".$key.".cache"; if(@filemtime($file)>=time()){ returnunserialize(file_get_contents($file)); }else{ @unlink($file)or$this->error(__line__,"failtounlink"); returnfalse; } }
//删除缓存文件 function__unset($key){ return$this->_unset($key); } function_unset($key){ if(@unlink($this->cache_dir."/".$key.".cache")){ returntrue; }else{ returnfalse; } }
//检查缓存是否存在,过期则认为不存在 function__isset($key){ return$this->_isset($key); } function_isset($key){ $file=$this->cache_dir."/".$key.".cache"; if(@filemtime($file)>=time()){ returntrue; }else{ @unlink($file); returnfalse; } }
//清除过期缓存文件 functionclear(){ $files=scandir($this->cache_dir); foreach($filesas$val){ if(filemtime($this->cache_dir."/".$val)<time()){ @unlink($this->cache_dir."/".$val); } } }
//清除所有缓存文件 functionclear_all(){ $files=scandir($this->cache_dir); foreach($filesas$val){ @unlink($this->cache_dir."/".$val); } } functionerror($msg,$debug=false){ $err=newException($msg); $str="<pre> <spanstyle='color:red'>error:</span> ".print_r($err->getTrace(),1)." </pre>"; if($debug==true){ file_put_contents(date('Y-m-dH_i_s').".log",$str); return$str; }else{ die($str); } } } ?>