PHP+smarty缓存控制(三种方法)详细讲解

1,使用insert函数使模板的一部分不被缓存

<?php
/*********************************************
*
* 文件名: index2.php
* 作 者: 史金波
* Email:
jspphp@126.com
*********************************************/
include_once(“smarty/libs/Smarty.class.php”); //包含smarty类文件

$smarty = new Smarty;//设置各个目录的路径,这里是安装的重点
$smarty->template_dir =”smarty/templates/templates”;
$smarty->compile_dir =”smarty/templates/templates_c”;
$smarty->config_dir = “smarty/templates/config”;
$smarty->cache_dir =”smarty/templates/cache”;

$smarty->caching = true;

$smarty->assign(“name”, “史金波”); //进行模板变量替换

function insert_myname(){
$name = “神雕大侠”;
return $name;
}

$smarty->display(“index2.tpl”);

?>

index2.tpl
<div>{insert name=”myname”}</div>
注意:红色的部分 就是要用这种格式,呵呵!!函数名字前缀为:insert_

、使用register_function阻止插件从缓存中输出
index.tpl:
<div>{current_time}{/div}

index.php:
function smarty_function_current_time($params, &$smarty){
return date(“Y-m-d H:m:s”);
}

$smarty=new smarty();
$smarty->caching = true;
$smarty->register_function(‘current_time’,’smarty_function_current_time’,false);
if(!$smarty->is_cached()){
…….
}
$smarty->display(‘index.tpl’);

注解:
定义一个函数,函数名格式为:smarty_type_name($params, &$smarty) type为function
name为用户自定义标签名称,在这里是{current_time} 两个参数是必须的,即使在函数中没有使用也要写上。两个参数的功能同上。

3、使用register_block使整篇页面中的某一块不被缓存
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) {
return $content;
}
$smarty = new Smarty;
$smarty->caching = true;
$smarty->register_block(‘dynamic’, ‘smarty_block_dynamic’, false);
if(!$smarty->is_cached()){
…….
}
$smarty->display(‘index.tpl’);

注解:
定义一个函数,函数名格式为:smarty_type_name($params, &$smarty) type为block
name为用户自定义标签名称,在这里是{dynamic} 两个参数是必须的,即使在函数中没有使用也要写上。两个参数的功能同上。

4、总结
(1)对缓存的控制能力:
使用register_function和register_block能够方便的控制插件输出的缓冲能力,可以通过第三个参数控制是否缓存,默认是缓存的,需要我们显示设置为false,正如我们试验中的所做的那”$smarty->register_function (‘current_time’,’smarty_function_current_time’,false);”但insert函数默认是不缓存的。并且这个属性不能修改。从这个意义上讲insert函数对缓存的控制能力似乎不如register_function和register_block强。
(2)使用方便性:
但是insert函数使用非常方便。不用显示注册,只要在当前请求过程中包含这个函数smarty就会自动在当前请求的过程中查找指定的函数。当然 register_function也可以做到不在运行时显示注册。但是那样做的效果跟其他模版函数一样,统统被缓存,并且不能控制。
如果你使用在运行时显示调用register_function注册自定义函数,那么一定要在调用is_cached()方法前完成函数的注册工作。否则在is_cached()这一步缓存文档将因为找不到注册函数而导致smarty错误



发表评论

您的电子邮箱地址不会被公开。

+ 66 = 73