Smarty缓存基础配置与清理方法
1. Smarty缓存的基础配置
//代码结束具体代码实现如下:
$smarty->cache_dir="目录名"; //指定并创建用于存放缓存文件的目录名称
$smarty->caching=true; //启用缓存功能;若设置为false,则缓存机制失效
$smarty->cache_lifetime=60; //设定缓存的有效时长,单位为秒2. Smarty缓存的使用与清理方法
//代码结束相关代码如下:
$smarty->display("cache.tpl", cache_id); //生成带有特定ID标识的缓存文件
$smarty->clear_all_cache(); //删除系统中存在的所有缓存文件
$smarty->clear_cache("index.php"); //仅清除针对index.php页面的缓存内容
$smarty->clear_cache("index.php", cache_id); //清除index.php页面中指定ID的缓存实现局部不缓存的两种方案
3. Smarty的局部缓存控制策略
第一种方案:使用insert_函数。该函数生成的区域默认不参与缓存,且此行为不可更改。
具体使用方法示例如下:
在index.php文件中:
function insert_get_time(){
return date("Y-m-d H:m:s");
}在HTML模板文件中:
{insert name="get_time"}
第二种方案:使用smarty_block机制。
定义一个block函数:smarty_block_name($params, $content, &$smarty){return $content;} //其中name代表该区域的名称
注册该block:$smarty->register_block('name', 'smarty_block_name', false); //第三个参数设为false,表示该区域不被缓存
模板中的调用写法为:{name}内容{/name}
也可以将其编写为block插件形式:
1) 创建一个名为block.cacheless.php的插件文件,并将其放置于smarty的plugins目录下
block.cacheless.php的具体内容如下:
<?php function smarty_block_cacheless($param, $content, &$smarty) {
return $content;
}
?> 2) 编写测试程序及对应的模板文件
示例程序文件名为testCacheLess.php
<?php include('Smarty.class.php');
$smarty = new Smarty;
$smarty->caching=true;
$smarty->cache_lifetime = 6;
$smarty->display('cache.tpl');
?> 所使用的模板文件为cache.tpl
已包含在缓存中的部分:{$smarty.now}
{cacheless}
未包含在缓存中的部分:{$smarty.now}
{/cacheless}
自定义缓存处理器的实现方式
4. 自定义缓存处理逻辑
通过设置cache_handler_func属性,可以指定一个自定义函数来处理缓存逻辑。
例如:
$smarty->cache_handler_func = "myCache";
function myCache($action, &$smarty_obj, &$cache_content, $tpl_file=null, $cache_id=null, $compile_id=null){
}该函数的主要作用是根据$action参数的值来判断当前执行的缓存操作类型:
switch($action){case "read"://读取缓存内容
case "write"://写入缓存
case "clear"://清空缓存
}通常建议使用md5($tpl_file.$cache_id.$compile_id)作为唯一的cache_id以确保唯一性
如有需要,可以使用gzcompress和gzuncompress函数对缓存内容进行压缩和解压以节省空间