Smarty之缓存,局部缓存

本文介绍Smarty模板引擎的缓存机制,包括全局缓存的配置与使用、局部缓存的多种控制方式,以及如何通过PHP赋值控制缓存,旨在提高网站性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

smarty缓存

把页面保存到到磁盘,下次访问直接返回保存内容。

不缓存浪费数据库性能,因为刷一次从数据库取一次数据


<?php
/*smarty缓存
解释:把页面保存到到磁盘,下次访问直接返回保存内容。
1.开启缓存
2配置缓存的生命周期
3配置是否缓存,是否从数据库取数据
4输出
*/

require('../../smarty3/libs/Smarty.class.php');
require('./mysmarty.class.php');
$smarty=new MySmarty();
//开启缓存
$smarty->caching=true;
//缓存生命周期
$smarty->cache_lifetime=20;
//缓存目录
$smarty->cache_dir='./cache';

//判断是否缓存;当没有缓存过或过了生命周期或改了模板就不缓,更新覆盖
if(!$smarty->isCached('temp6.html')){
	$conn=mysqli_connect('localhost','root','123456','boolshop');
	$sql ='set names utf8';
	mysqli_query($conn,$sql);
	$sql ='select * from goods limit 5';
	$rs=mysqli_query($conn,$sql);
	$goods=array();
	while($row=mysqli_fetch_assoc($rs)){
		$goods[]=$row;
	}

	// 不缓存就不经过这块,不会输出下面的字;
	$smarty->assign('goods',$goods);

	echo '我不是缓存哟~ o(* ̄▽ ̄*)ブ ';
}


$smarty->display('temp6.html');

?>


局部缓存
1 在一个标签中控制:{$time nocache} ;把标了这个nocache的还是php语言,走php的,看cache文件就知道了
2 控制一片不缓存 {nocache} {/nocache} 
3 php里赋值时控制 $smarty->assign('time',$time,true);
4 用函数控制 

function insert_hi(){
	return 'hello my world';
}
html里

{insert name='hi'}


在函数里还可以加参数

function insert_hi($parm,$smarty){
	return 'hello my world'." ".$parm['city'];
}

html里

	<p>
	{$time}
	{insert name='hi' city='shanghai'}
	</p>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值