Ectouch中缓存管理函数
更新时间:2015-10-21 点击量:1996
在做Ectouch开发时,需要用到缓存函数,虽然有write_static_cache($cache_name,$caches)
及read_static_cache($cache_name)
函数,但是不能设置缓存期限。
参照Thinkphp里的S缓存管理函数写了个类似的函数s_cache()
替代,代码如下:
/** * 缓存管理 * @param mixed $name 缓存名称 * @param mixed $value 缓存值 * @param mixed $expire 缓存期限 秒为单位 ,0为永久缓存 * @return mixed */ function s_cache($name,$value='',$expire=0) { if ((DEbug_MODE & 2) == 2) {//调试模式不使用缓存 return false; } static $_cache = array();//静态存储 $name=md5($name); $filename = ROOT_PATH . 'data/cache/expire/'. $name . '.php'; if(''=== $value){ // 读取缓存 if (!is_file($filename)) { return false; } if (isset($_cache[$name])){ $content= $_cache[$name]; }else{ $content = file_get_contents($filename); $_cache[$name]=$content; } if( false !== $content) { $expire = (int)substr($content,8, 12); if($expire != 0 && time() > filemtime($filename) + $expire) {//检查缓存是否过期 //缓存过期删除缓存文件 unlink($filename); return false; } $content = substr($content,20, -3); $content = unserialize($content); return $content; }else { return false; } }elseif(is_null($value)) { // 删除 unlink($filename); }else { // 缓存写入 $cache_dir = dirname($filename); if(!is_dir($cache_dir)) mkdir($cache_dir,0777,true); $expire=is_numeric($expire)?$expire:0; $data = serialize($value); $data = "<?php\n//".sprintf('%012d',$expire).$data."\n?>"; $_cache[$name] = $data; $result = file_put_contents($filename,$data,LOCK_EX); if($result) { return true; }else { return false; } } }
如果文章对您有帮助,就打赏一个吧
«上一篇:商派ecshop的短信服务二次开发 下一篇:基于Ecshop/Ectouch微分销插件的开发(一):模型设计»