smarty缓存

smarty缓存其实就是把页面内容保存在磁盘上,下次(短期内不会变化)访问相同页面就直接返回保存的内容,这样在一定程度上减轻了数据库和带宽的压力,同时也减少了用户的等待时间。

下面介绍smarty缓存的用法:

1:开启缓存 —— $smarty->caching = true;

2:配置缓存的生命周期,如: —— $smarty->cache_lifetime = 10;(单位为秒)

3:配置缓存的目录,用于存储缓存文件,如: —— $smarty->cache_dir = './cache';

4:以从数据库取数据为例,判断是否缓存并是否从数据库取数据,最后输出,具体代码如下:

if(!$smarty->isCached('01.html')) { // 判断01.html运行的内容有没有缓存起来

    $conn = mysql_connect('localhost','root','111111');
    mysql_query('set names utf8',$conn);
    mysql_query('use test',$conn);

    $sql = 'select goods_id,goods_name,shop_price from goods limit 5';
    $rs = mysql_query($sql,$conn);

    $goods = array();
    while($row = mysql_fetch_assoc($rs)) {
        $goods[] = $row;
    }

    // echo '我走了数据库';
    
    // 把数组赋给smarty对象
    $smarty->assign('goods',$goods);
}
$smarty->display('01.html');
<table border="1px">
        <tr><td>序号</td><td>商品名</td><td>商品价格</td></tr>
        {foreach $goods as $k=>$g}
        <tr {if $g@first} bgcolor=blue {/if}
        ><td>{$g@iteration}</td><td>{$g.goods_name}</td><td>{$g.shop_price}</td></tr>
        {/foreach}
    </table>


另外,smarty在页面缓存的情况下,可以设置部分内容不缓存,比如页面的股票信息部分,时间等,这些不适宜缓存

在smarty中,想控制局部不缓存,方法非常多
    1:在标签中控制,该标签不缓存 {$标签 nocache}
    2:可以控制一片标签,不缓存{nocache}xxxxxx{/nocache}控制的区域比较大
    3:在php中,赋值时,就控制不缓存[smarty3新增]
    注意:不缓存的标签,要保证总能从php处得到值

$time = time();
$smarty->assign('time1',$time);
$smarty->assign('time2',$time,true); // 第3个参数是nocache,为true,说明不缓存

<h2>当前时间{$time1|date_format:"%Y-%m-%d %H:%M:%S"}</h2>
    <h2>当前时间{$time1|date_format:"%Y-%m-%d %H:%M:%S" nocache}</h2>
    {nocache}<h2>当前时间{$time1|date_format:"%Y-%m-%d %H:%M:%S"}</h2>{/nocache}
    
    <h2>当前时间{$time2|date_format:"%Y-%m-%d %H:%M:%S"}</h2>
    4:{insert name="xxx" parm1="v1" parm2="v2"}这个方式来写
    原理是,调用 insert_xxx(array(parm1="v1" parm2="v2"))的返回值,来显示的

function insert_welcome($parm) {
    return '你好'.$parm['age']. rand(1000,9999);
}
<p>{insert name="welcome" age="28"}</p>


注:有时出于调试目的,临时不让缓存,但又不想修改主代码,可以加1选项

$smarty->force_cache = true;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值