专注于互联网--专注于架构

最新标签
网站地图
文章索引
Rss订阅

首页 »PHP教程 » smarty缓存:smarty缓存Cache控制 »正文

smarty缓存:smarty缓存Cache控制

来源: 发布时间:星期一, 2009年1月12日 浏览:12次 评论:0
  smarty提供了强大缓存Cache功能但有时我们并不希望整篇文档都被缓存Cache而是有选择缓存Cache某部分内容或某部分内容不被缓存Cache例如你在页面上端使用个带有广告条位置模板广告条可以包含任何HTML、图象、FLASH等混合信息. 因此这里不能使用个静态链接同时我们也不希望该广告条被缓存Cache. 这就需要在 insert 指定同时需要取广告条内容信息smarty也提供了这种缓存Cache控制能力

  我们可以使用{insert}使模板部分不被缓存Cache

  可以使用$smarty->register_function($params,&$smarty)阻止插件从缓存Cache中输出

  还可以使用$smarty->register_block($params,&$smarty)使整篇页面中块不被缓存Cache

  下面我们真对个简单需求分别介绍说明这 3种控制缓存Cache输出思路方法

  需求:被缓存Cache文档中当前时间不被缓存Cache随每次刷新而变化

  1、使用insert使模板部分不被缓存Cache

  index.tpl:

  <div>{insert name="get_current_time"}</div>

  index.php

function insert_get_current_time{
     date("Y-m-d H:m:s");
}
$smarty= smarty;
$smarty->caching = true;
(!$smarty->is_cached){
    .......
}
$smarty->display('index.tpl');


  注解:

  定义名格式为:inser_name(.gif' /> $params, object &$smarty),

  参数可选如果在模板insert思路方法中需要加入其他属性就会作为传递给用户定义

  如:{insert name='get_current_time' local='zh'}

  在get_current_time中我们就可以通过$params['local']来获得属性值

  如果在get_current_time中需要用到当前smarty对象思路方法或属性就可以通过第 2个参数获得

  这时你会发现index.tpl已被缓存Cache但当前时间却随每次刷新在不断变化

  2、使用register_function阻止插件从缓存Cache中输出

  index.tpl:

<div>{current_time}{/div}
index.php:
function smarty_function_current_time($params, &$smarty){
     date("Y-m-d H:m:s");
}
$smarty= smarty;
$smarty->caching = true;
$smarty->register_function('current_time','smarty_function_current_time',false);
(!$smarty->is_cached){
    .......
}
$smarty->display('index.tpl');


  注解:

  定义名格式为:smarty_type_name($params, &$smarty)

  type为function

  name为用户自定义标签名称在这里是{current_time}

  两个参数是必须即使在中没有使用也要写上两个参数功能同上

  3、使用register_block使整篇页面中块不被缓存Cache

  index.tpl:

<div align='center'>
Page created: {"0"|date_format:"%D %H:%M:%S"}
{dynamic}
Now is: {"0"|date_format:"%D %H:%M:%S"}
... do other stuff ...
{/dynamic}
</div>
index.php:
function smarty_block_dynamic($param, $content, &$smarty) {
$content;
}
$smarty = Smarty;
$smarty->caching = true;
$smarty->register_block('dynamic', 'smarty_block_dynamic', false);
(!$smarty->is_cached){
    .......
}
$smarty->display('index.tpl');




  注解:

  定义名格式为:smarty_type_name($params, &$smarty)

  type为block

  name为用户自定义标签名称,在这里是{dynamic}

  两个参数是必须即使在中没有使用也要写上两个参数功能同上

  4、整理总结

  (1)对缓存Cache控制能力:

  使用register_function和register_block能够方便控制插件输出缓冲能力可以通过第 3个参数控制是否缓存Cache默认是缓存Cache需要我们显示设置为false正如我们试验中所做那样“$smarty->register_function('current_time','smarty_function_current_time',false);”

  但insert默认是不缓存Cache并且这个属性不能修改从这个意义上讲insert对缓存Cache控制能力似乎不如register_function和register_block强

  (2)使用方便性:

  但是insert使用非常方便不用显示注册只要在当前请求过程中包含这个smarty就会自动在当前请求过程中查找指定

  当然register_function也可以做到不在运行时显示注册但是那样做效果跟其他模版统统被缓存Cache并且不能控制

  如果你使用在运行时显示register_function注册自定义那么定要在is_cached思路方法前完成注册工作

  否则在is_cached步缓存Cache文档将找不到注册而导致smarty



0

相关文章

读者评论

发表评论

  • 昵称:
  • 内容: