您的位置:首页 > 编程语言 > PHP开发

PHP smarty缓存

2016-07-28 14:27 543 查看
缓存一个页面

test.php

<?php

//定义该页面缓存文件存放的路径
$filename = "../cache/cachetest.html";

//定义缓存有效期
$cachetime = 5;

//判断缓存文件是否存在
if(!file_exists($filename) || filemtime($filename)+$cachetime<time())
{
//开启内存缓存
ob_start();

include("../init.inc.php");
include("../DBDA.php");
$db = new DBDA();

$sql = "select * from car";

$attr = $db->Query($sql);

$smarty->assign("car",$attr);
$smarty->display("test.html");

//从内存缓存中获取页面代码
$content = ob_get_contents();

//将获取到的内容存放到缓存文件
file_put_contents($filename,$content);

//清掉内存缓存
ob_flush();

echo "######################################";

}
else
{
include($filename);
}


test.html

<body>
<h1>汽车信息</h1>
<table width="100%" border="1" cellpadding="0" cellspacing="0">
<tr>
<td>代号</td>
<td>汽车名称</td>
<td>油耗</td>
<td>价格</td>
</tr>

<{foreach $car as $v}>
<tr>
<td><{$v[0]}></td>
<td><{$v[1]}></td>
<td><{$v[4]}></td>
<td><{$v[7]}></td>
</tr>
<{/foreach}>

</table>
</body>








分页缓存

testa.php

<?php

//取当前页
$p=1;
if(!empty($_GET["page"]))
{
$p = $_GET["page"];
}
//定义缓存文件存放路径
$filename = "../cache/cahetesta{$p}.html";

//判断
if(!file_exists($filename) || filemtime($filename)+30<time())
{
ob_start();

include("../init.inc.php");
include("../DBDA.php");
$db = new DBDA();

include("page.class.php");

$szs = "select count(*) from car";
$zs = $db->StrQuery($szs);

$page = new Page($zs,5);
$xinxi = $page->fpage();

$sql = "select * from car ".$page->limit;

$attr = $db->Query($sql);

$smarty->assign("car",$attr);
$smarty->assign("xinxi",$xinxi);
$smarty->display("testa.html");

$nr = ob_get_contents();

file_put_contents($filename,$nr);

ob_flush();

echo "################################################";
}
else
{
include($filename);
}


testa.heml

<body>
<h1>汽车信息</h1>
<table width="100%" border="1" cellpadding="0" cellspacing="0">
<tr>
<td>代号</td>
<td>汽车名称</td>
<td>油耗</td>
<td>价格</td>
</tr>

<{foreach $car as $v}>
<tr>
<td><{$v[0]}></td>
<td><{$v[1]}></td>
<td><{$v[4]}></td>
<td><{$v[7]}></td>
</tr>
<{/foreach}>

</table>
<div><{$xinxi}></div>
</body>




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: