這里我們就要對(duì)這個(gè)緩沖區(qū)做一下文章了,在php輸出內(nèi)容之前,我們?nèi)〕鼍彌_區(qū)的內(nèi)容(這里就是渲染好的模板內(nèi)容了),然后將其寫入一個(gè)靜態(tài)文件中并設(shè)置過(guò)期時(shí)間,當(dāng)下次用戶訪問(wèn)該頁(yè)面的時(shí)候,如果該靜態(tài)文件存在并且在有效期內(nèi),我們就直接將該靜態(tài)文件展示給用戶看,否則重寫靜態(tài)文件。
代碼實(shí)現(xiàn)
數(shù)據(jù)庫(kù)連接,用到了單例模式。
Database.php
<?php
class Database {
//用于保存實(shí)例化對(duì)象
private static $instance;
//用于保存數(shù)據(jù)庫(kù)句柄
private $db = null;
//禁止直接實(shí)例化,負(fù)責(zé)數(shù)據(jù)庫(kù)連接,將數(shù)據(jù)庫(kù)連接句柄保存至私有變量$db
private function __construct($options) {
$this->db = mysqli_connect($options['db_host'], $options['db_user'], $options['db_password'], $options['db_database']);
}
//負(fù)責(zé)實(shí)例化數(shù)據(jù)庫(kù)類,返回實(shí)例化后的對(duì)象
public static function getInstance($options) {
if (!(self::$instance instanceof self)) {
self::$instance = new self($options);
}
return self::$instance;
}
//獲取數(shù)據(jù)庫(kù)連接句柄
public function db() {
return $this->db;
}
//禁止克隆
private function __clone() {
// TODO: Implement __clone() method.
}
//禁止重構(gòu)
private function __wakeup() {
// TODO: Implement __wakeup() method.
}
}
用于靜態(tài)化頁(yè)面
Cache.php
<?php
class Cache {
public function index($options) {
//判斷文件是否存在,判斷是否過(guò)期
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();
}
//開(kāi)啟緩存區(qū),這后面的內(nèi)容都會(huì)進(jìn)緩存區(qū)
ob_start();
//引入模板文件(模板會(huì)渲染數(shù)據(jù))
require_once ('templates/index.php');
//取出緩存區(qū)內(nèi)容(在這里是渲染后的模板),將其保存(默認(rèn)會(huì)覆蓋原來(lái)的)為index.shtml(static html)
file_put_contents('shtml/index.shtml', ob_get_contents());
}
}
}
//數(shù)據(jù)庫(kù)配置信息
$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>首頁(yè)</title>
</head>
<body>
<?php foreach ($res as $item) {?>
<p>姓名:<?php echo $item[1]?></p>
<p>密碼:<?php echo $item[2]?></p>
<?php }?>
</body>
</html>
瀏覽器訪問(wèn) localhost/Cache.php
更多關(guān)于云服務(wù)器,域名注冊(cè),虛擬主機(jī)的問(wèn)題,請(qǐng)?jiān)L問(wèn)西部數(shù)碼官網(wǎng):m.ps-sw.cn