smarty缓存技术

后台:

<?php
//要求:当存在缓存文件,直接输出,不存在缓存文件,自己创建缓存,输出
//步骤:
//定义该页面存放缓存文件的路径
$filename="../../cache/cache.html";
//定义缓存有效期
$cachetime=5;
//判断是否存在缓存或是否过期
if(!file_exists($filename) || time()-filemtime($filename)>$cachetime)//现在的时间-缓存创建时间
{
    //开启内存缓存--将下面执行后的页面代码存到内存
    ob_start();
    include ('../../init.inc.php');
    include ("../../DBDA.php");
    $dx=new DBDA();
    $sql="select * from car";
    $attr=$dx->Query($sql);
    $smarty->assign("car",$attr);
    $smarty->display("main.html");
    //获取内存缓存里的页面代码
    $content=ob_get_contents();
    //将页面代码存到缓存文件里
    file_put_contents($filename,$content);
    //清除内存缓存并输出显示
    ob_flush();
    echo "#########";//代表第一次执行
    }
else
{
    include ($filename);//如果存在缓存,直接读取
    }
//如果刷新页面没有改变的话,可能是有缓存文件,为了避免这样,需设置缓存有效期 

前台:

<body>
<table border="1" width="80%" align="center"  cellpadding="0" cellspacing="0">
<tr>
<th>代号</th>
<th>汽车名称</th>
<th>油耗</th>
<th>价格</th>
</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>

分页缓存:

后台:

<?php
//分页缓存
//要求:实现每一页都缓存
//步骤:
//取当前页
$p=1;
if(!empty($_GET["page"]))
{
    $p = $_GET["page"];
}
//定义缓存文件存放路径
$filename = "../../cache/cahetesta{$p}.html";
//定义缓存有效期
$cachetime=5;
//判断缓存是否存在或是否过期
if(!file_exists($filename) || time()-filemtime($filename)>$cachetime)
{
    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("maina.html");
    //获取内存缓存页面代码
    $nr = ob_get_contents();
    //将页面代码存放到缓存文件下
    file_put_contents($filename,$nr);
    //清除内存缓存并输出
    ob_flush();
    
    echo "##########################";//用来检查是否是第一次访问或过期与否
}
else
{
    include($filename);
}

前台:

<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>
原文地址:https://www.cnblogs.com/jinshui/p/5708008.html