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); //仅清除指定模板文件中对应特定ID的缓存
利用insert与block实现局部缓存
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函数对缓存内容进行压缩和解压以节省空间