用于静态化页面
Cache.php
<?php
class Cache {
public function index($options) {
//判断文件是否存在,判断是否过期
if (is_file('shtml/index.shtml') && (time() - filemtime('shtml/index.shtml') < 300)) {
require_once ('index.shtml');
}else {
require_once ('Database.php');
$con = Database::getInstance($options)->db();
$sql = "SELECT * FROM pro_test";
$exe_res = mysqli_query($con, $sql);
$res = mysqli_fetch_all($exe_res);
try{
if (!$res) {
throw new Exception("no result");
}
}catch (Exception $e) {
echo 'Message: ' .$e->getMessage();
}
//开启缓存区,这后面的内容都会进缓存区
ob_start();
//引入模板文件(模板会渲染数据)
require_once ('templates/index.php');
//取出缓存区内容(在这里是渲染后的模板),将其保存(默认会覆盖原来的)为index.shtml(static html)
file_put_contents('shtml/index.shtml', ob_get_contents());
}
}
}
//数据库配置信息
$options = [
'db_host' => 'mysql',
'db_user' => 'root',
'db_password' => 'localhost',
'db_database' => 'pro_shop',
];
$obj = new Cache();
$obj->index($options);
template/index.php
<!DOCTYPE>
<html>
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<?php foreach ($res as $item) {?>
<div>姓名:<?php echo $item[1]?></div>
<div>密码:<?php echo $item[2]?></div>
<?php }?>
</body>
</html>
浏览器访问 localhost/Cache.php



更多关于PHP相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。







