smarty缓存机制

来源:互联网 发布:c语言怎么控制光标 编辑:程序博客网 时间:2024/06/05 12:01

一、Smarty缓存的几种方式
缓存机制中,分为全局缓存、部分缓存、局部缓存三种方式,后面会一一讲述,下面是缓存设置前,Smarty类方法基本目录设置如下:
smarty>Smarty();smarty->template_dir = ROOT./templates;//smarty->compile_dir = ROOT./templatesc;//smarty->cache_dir = ROOT./cache;//smarty->caching = true;//是否开启缓存,值为0,1,2,0则不开启:1则开启缓存:2则可设置特殊缓存,即在加载模板页前,对局部进行缓存时间的特殊设定,后面会讲到;可不写,默认为true-开启
smarty>cachelifetime=3600;//3600smarty->compile_check = true;//是否进行编译,可不写,默认为true
缓存机制中调用模板生成缓存页面,用的一个display()方法,将会在后文中用到,这里先讲解一下:
smarty>display(stringtemplate[,stringcacheid[,stringcompileid]]);templatecacheidcompileid使Smarty1Smartysmarty->display(‘index.tpl’);
而这条语句,有一个很大的缺陷,就是一个模板即一个模板页面,只生成一个缓存,而我们知道,大多网站的多数页面后面会接一些参数或不同页面调用同一个模板,比如:
http://blog.unvs.cn/archives/2012_9.html
http://blog.unvs.cn/archives/2012_8.html
http://blog.unvs.cn/archives/2012_7.html
比方这些是调用的同一个模板生成的页面,但是又必须生成3个缓存,使用上面的语句肯定做不到,这里我们要想到一开始讲到的第二个可选参数cache_id,用一个缓存号,来区分同一个模板生成不同的页面及缓存,代码实例:
cacheid=_GET[‘id’];//url中的id参数值
smarty>display(index.tpl,cache_id);//将缓存号加入,即可完成–同一模板–不同参数–不同缓存 的功能;
到这里,有人发现,如果我的页面不止一个参数,那是不是得全部解析出来并做为缓存号?这里有一个更好的方法,推荐给大家,也是网上大多赞同的。(其实,上面一段是’废话‘,可去掉,但为了循序渐进,更好理解而写的过渡,谅)
推荐的方法是:你可以直接将整个当前URL获取下来,作为cache_id加入缓存,这样无论它多少个参数,都不会存在同一个缓存页,
代码实例:
url=_SERVER[‘REQUEST_URI’];//获取当前页URL,有的将url进行md5加密,亦可
smarty>display(index.tpl,url);
2、部分缓存方式
定义:意思就是,网站系统的部分页面进行缓存,而一些页面不进行缓存,比方网站的注册、登录处理页面可不进行缓存。
一种处理方式:在display()方法前或后面,将此模板缓存进行一次清除操作,注意保持两者参数必须一致;
代码实例:
smarty>clearcache(index.tpl);//displaysmarty->display(“index.tpl”);//与clear_cache方法参数必须一致
另一种处理方式:原理是一样的,因为部分缓存相当于两种情况,你可以另写一个display方法进行重构,其中一个参数判断是否进行缓存,若不,则进行clear_cache()方法处理,否则进行缓存;
代码实例:
function display(tempname,cache_id = null,iscache=true)if($iscache)$smarty>clearcache(index.tpl,$cacheid);$smarty>display(index.tpl,$cacheid);//绿else$smarty>display(index.tpl,$cacheid);self::display(temp_name, cacheid,false);//312a使SMartynocachesmarty3.1.8smarty2+tplhtmlnocache/nocachesmarty->assign(“time”,time());
模板页面:{nocache}<{time}>{/nocache}  
b、注册块方法,实现不缓存  
写一个no_cached方法,并调用smarty注册块函数将方法进行注册,即可实现,直接贴实例。  
代码实例:  
处理页面:
smarty->assign(“time”,time());
function no_cached(param,content){//参数paramcontent为不缓存内容
return content;  
}
smarty->register_block("no_cached", “no_cached”, false);//注册块方法:register_block(tplfunc,reg_func, cacheable);//123falsenocached<$time>/nocachedc使smarty4iscachediscached(temp_tpl[, cacheid])temp_tpl参数为模板页,cacheidif(!smarty>iscached(index.tpl))////smarty->display(‘index.tpl’);//加载模板页

2 0
原创粉丝点击