SMARTY静态缓存

在templates文件夹下创建huancunpage.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>

<body>
<h1>民族信息</h1>
<table width="100%" border="1" cellpadding="0" cellspacing="0">
    <tr>
        <td>代号</td>
        <td>名称</td>
        <td>操作</td>
    </tr>
    
    <{foreach $arr as $v}>
    <tr>
        <td><{$v[0]}></td>
        <td><{$v[1]}></td>
        <td><a href="del.php?code=<{$v[0]}>">删除</a><a href="update.php?code=<{$v[0]}>">修改</a></td>
    </tr>
    <{/foreach}>
    
</table>
<div><{$page}></div>

<a href="add.php">添加数据</a>

</body>
</html>

在main文件夹下创建huancunpage.php

<?php
//当前页
$p = 1;
if(!empty($_GET["page"]))
{
    $p = $_GET["page"];
}

//定义一个缓存页面的位置
$filename = "../cache/huancunpage{$p}.html"; //一般缓存文件放在cache文件夹里

//加缓存时间
$sj = 10;

//判断当前页面是否要使用缓存
if(file_exists($filename) && (filemtime($filename)+$sj) >time())//注意时间条件的判断
{
    //如果存在缓存页面就显示缓存文件
    include($filename);
}
else
{
    //重新生成缓存文件
    ob_start(); //开启内容缓冲区(缓存)
    
    require("../init.inc.php");
    require("../DBDA.php");
    require("../page.class.php");//引入分页类文件
    $db = new DBDA();
    $ztss = "select count(*) from nation";
    $zts = $db->StrQuery($ztss);
    
    $page = new Page($zts,5);
    
    $sql = "select * from nation ".$page->limit;
    $arr = $db->Query($sql);

    $smarty->assign("arr",$arr);
    $smarty->assign("page",$page->fpage());
    $smarty->display("huancunpage.html");
    
    
    $str = ob_get_contents(); //从内容缓存里面获取内容
file_put_contents($filename,$str); //将获取到的内容放到缓存文件里面 ob_flush(); //清空内存缓存 echo "########################################";//重新加载时显示,显示缓存页面时不显示 }

访问huancunpage.php的显示结果:

 第一张是从服务器读取的数据,第二张是在缓存时间内读取的缓存文件。

 做分页的缓存就是把每一张分页的内容分别缓存。

原文地址:https://www.cnblogs.com/gaobint/p/6773475.html