php smarty模版引擎中的缓存应用

yipeiwu_com5年前PHP代码库
1,Smarty缓存的配置:
复制代码 代码如下:

$smarty->cache-dir="目录名"; //创建缓存目录名
$smarty->caching=true; //开启缓存,为false的时候缓存无效
$smarty->cache_lifetime=60; //缓存时间,单位是秒

2,Smarty缓存的使用与清除
复制代码 代码如下:

$marty->display("cache.tpl",cache_id); //创建带ID的缓存
$marty->clear_all_cache(); //清楚所有缓存
$marty->clear_cache("index.php"); //清楚index.php中的缓存
$marty->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");
}
index.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}<br>
{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来压缩和解压

相关文章

PHP 出现乱码和Sessions验证问题的解决方法!

在PHP脚本中读出中文或者其他语言文字为乱码的时候,首先检查你的文件格式是不是用UTF8的编码格式保存的。如果不是请用UltraEdit...等一些对UTF8支持转换的工具转换一下,最好...

PHP实现自动对图片进行滚动显示的方法

本文实例讲述了PHP实现自动对图片进行滚动显示的方法。分享给大家供大家参考。具体如下: 指定某个图片目录,该程序自动在页面上滚动展示每一张图片,使用方法: 1. 创建一个幻灯片的图像文件...

php实现的css文件背景图片下载器代码

本文实例讲述了php实现的css文件背景图片下载器代码。分享给大家供大家参考。具体实现方法如下: 下载css文件里面的背景图片是我们这些盗版份子长期搞的事情,下载个css图片下载器常出现...

PHP实现websocket通信的方法示例

本文实例讲述了PHP实现websocket通信的方法。分享给大家供大家参考,具体如下: 执行方法: 首先先修改server.php与index.html的ip 通过命令行执行 [php路...

php中根据变量的类型 选择echo或dump

此时,is_scalar内置函数就派上用场了。 is_scalar -- 检测变量是否是一个标量 标量变量是指那些包含了 integer、float、string 或 boolean的变...