来源:http://blog.sina.com.cn/s/blog_9ccc92dd01016ovt.html
smarty的缓存机制不是太完美,只会断定当前的缓存文件是否过期,如果过时就写入新的缓存,这样缓存只会越来越多,硬盘也总有hold不住的那天。那么,咱们就来改良下smarty使之可能定时自动清空缓存。1、翻开Smarty.class.php在smarty这个类中增加一个变量:
1,设定清除时间 var $clear_cache_time = '2 10';
2,在smarty类中增添两个方式:一个履行自动清空缓存的义务,一个判定是否须要清空
//缓存设定时间自动删除
var $clear_cache_time = '1 2';
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;
}
//$smarty -> compile_dir 这里是设定的目录
$cachetag = "E:/WampSever/wamp/study/compile/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的进程中,都进行自动清空缓存的操作