这里我们就要对这个缓冲区做一下文章了,在php输出内容之前,我们取出缓冲区的内容(这里就是渲染好的模板内容了),然后将其写入一个静态文件中并设置过期时间,当下次用户访问该页面的时候,如果该静态文件存在并且在有效期内,我们就直接将该静态文件展示给用户看,否则重写静态文件。代码实现数据库连接,用到了单例模式。 Database.php
db = mysqli_connect($options['db_host'], $options['db_user'], $options['db_password'], $options['db_database']);
}
//负责实例化数据库类,返回实例化后的对象
public static function getInstance($options) {
if (!(self::$instance instanceof self)) {
self::$instance = new self($options);
}
return self::$instance;
}
//获取数据库连接句柄
public function db() {
return $this->db;
}
//禁止克隆
private function __clone() {
// TODO: Implement __clone() method.
}
//禁止重构
private function __wakeup() {
// TODO: Implement __wakeup() method.
}
} 用于静态化页面 Cache.php
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
首页
姓名:
密码:
浏览器访问 localhost/Cache.php 以上就是PHP页面静态化之纯静态与伪静态用法详解的详细内容,更多请关注 模板之家(www.mb5.com.cn) 其它相关文章! |