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>

 

转载于:https://www.cnblogs.com/lzzhuany/p/4839684.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值