·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设问答 >> 改进smarty使之能够定时自动清空缓存

改进smarty使之能够定时自动清空缓存

作者:佚名      网站建设问答编辑:admin      更新时间:2022-07-23

smarty的缓存机制不是太完善,只会判断当前的缓存文件是否过期,如果过期就写入新的缓存,这样缓存只会越来越多,硬盘也总有hold不住的那天。那么,我们就来改进下smarty使之能够定时自动清空缓存

1、打开Smarty.class.php在smarty这个类中添加一个变量:

 /**
  * @每2天 早上10点清空缓存
  */ 
 var $clear_cache_time = ’2 10′;

2、在smarty类中添加两个方法:一个执行自动清空缓存的任务,一个判断是否需要清空

 private function autoClearCache()
 {
  if($this->checkClearTime()){
   $this->clear_all_cache(); //删除所有已过期的缓存
  }
 }
 
 private function checkClearTime()
 {
  $CacheParam = explode(” “,$this->clear_cache_time);

  if(!$this->clear_cache_time || count($CacheParam) !== 2)
  {
   return false;
  }

  if(date(‘H’) != $CacheParam[1])
//当前的 小时 不为 设定的需要清空的 小时,返回false
  {
   return false;
  }

  $cachetag = $this->compile_dir.”/autoclear.tag”;
//设定一个文件,用于记录上次自动清空的时间

        if (file_exists($cachetag))
  {
            $filetime = date(‘U’, filemtime($cachetag));
//返回文件内容上次修改的时间

   if(date(‘d’)-date(“d”,$filetime) == $CacheParam[0])
//如果现在距离上次文件修改时间的天数 为 设定的自动清空缓存的天数
   {
    return true ;
   } else {
    return false ;
   }
  }

  file_put_contents($cachetag,date(“Y-m-d H:i:s”));
//如果不存在autoclear.tag文件,则创建并写入当前时间

  return true;
 }

3、在smarty本来的fetch方法的头部加上一句

$this->autoClearCache();
//也就是每次执行smarty的过程中,都进行自动清空缓存的操作

ok,这样简单的一个通过设定每几天 某个时间段内自动清空缓存的操作就完成了。当然,如果觉得功能满足不了自己的要求,那么开动自己的脑筋,敲敲最爱的键盘,开始自己的smarty自动清空缓存之路吧。

来源:http://www.yanglongji.com/php/smarty-cache-auto-clear/ 转载请注明出处。