zoukankan      html  css  js  c++  java
  • smarty实现缓存

    首先需要在mySmarty中添加配置信息,开启缓存,设置缓存文件存放目录,设置缓存时间
    缓存可以实现减少访问数据库,减轻数据库压力,访问一次数据库,形成静态页面,下次直接调用这个页面,也可以用nocache标签实现局部不缓存

    在mysmarty类中添加的语句

    		$this->cache_dir='./cache';//缓存文件存放目录
    
    		//开启缓存
    		$this->caching=true;
    		//配置缓存的生命周期
    		$this->cache_lifetime=3600;//单位是秒
    

     控制页面01.php

    <?php
    //演示缓冲
    require('../../smarty3/libs/smarty.class.php');
    
    
    require('./mySmarty.php');
    
    //定义方法
    function insert_welcome(){
    	return 123;
    }
    //创建对象
    $smarty=new mySmarty();
    
    //是否开启缓存
    
    $arr=array();
    if(!$smarty->isCached('01.html')){
    	$conn=mysql_connect('localhost','root','111111');
    	mysql_query('use boolshop',$conn);//选库
    	mysql_query('set names utf8',$conn);//设置编码
    	$sql='select goods_id,goods_name,goods_number,shop_price from goods limit 5';
    	$rs=mysql_query($sql,$conn);
    	
    	while(($row=mysql_fetch_assoc($rs))!==false){ 
    		$arr[]=$row;
    	}
    	echo '我走了数据库';
    }
    //$smarty->clearCache('01.html');//强制清除缓存
    $smarty->assign('suiji',rand(),true);//如果第三个参数是true,则这个变量不缓存
    $smarty->assign('goods',$arr);
    $smarty->display('01.html');
    
    
    ?>
    

     显示页面01.html

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>显示数据</title>
        <style type="text/css">
    {literal}
    p{
        font-size:25px;
        background:green;
    }
        
    {/literal}
        </style>
    
    </head>
    <body>
    <p>这里是一个随机数{rand()*100 nocache}添加nocache属性不缓存(局部的)<p>
    <p>这是用assign传的值{$suiji}</p>
    用foreach遍历数组<br/>
    {foreach from=$goods key='key' item='v'}
        <p>
         id号:{$v['goods_id']},商品名字:{$v['goods_name']},商品价格{$v['shop_price']},商品储存量   {$v['goods_number']}
    
        </p>
    {/foreach}
    <p>{insert name='welcome'  nocache}</p>
    </body>
    </html>
    
  • 相关阅读:
    [HAOI2015]树上操作(树链剖分)
    树链剖分——解决树上路径问题利器
    [CodeForces 833B] The Bakery(数据结构优化dp)
    [国家集训队]最长双回文串(马拉车)
    [国家集训队]拉拉队排练(Manacher)
    【ATcoder】AtCoder Beginner Contest 159 题解
    蒟蒻的数列[BZOJ4636](线段树)
    Manacher马拉车算法——解决最长回文子串问题
    HDU 1501 Zipper (记忆化搜索)
    HDU 1428 漫步校园 (dfs+记忆化搜索dfs)
  • 原文地址:https://www.cnblogs.com/lzzhuany/p/4839684.html
Copyright © 2011-2022 走看看