下面的代码是否显示了一种可接受的方式来缓存完全构建的页面和数据库查询?
已构建页面的缓存从__construct
控制器中的 开始,然后以 结束__destruct
,在此示例中,所有页面默认缓存 15 分钟到一个文件。
查询缓存已完成,apc
它们在每个查询的指定时间内存储在内存中。在实际站点中,apc 缓存还有另一个类,以便可以根据需要进行更改。
我的目标是构建最简单的 mvc,我失败了还是走在正确的轨道上?
控制器
//config
//autoloader
//initialiser -
class controller {
var $cacheUrl;
function __construct(){
$cacheBuiltPage = new cache();
$this->cacheUrl = $cacheBuiltPage->startFullCache();
}
function __destruct(){
$cacheBuiltPage = new cache();
$cacheBuiltPage->endFullCache($this->cacheUrl);
}
}
class forumcontroller extends controller{
function buildForumThread(){
$threadOb = new thread();
$threadTitle = $threadOb->getTitle($data['id']);
require 'thread.php';
}
}
模型
class thread extends model{
public function getTitle($threadId){
$core = Connect::getInstance();
$data = $core->dbh->selectQuery("SELECT title FROM table WHERE id = 1");
return $data;
}
}
数据库
class database {
public $dbh;
private static $dsn = "mysql:host=localhost;dbname=";
private static $user = "";
private static $pass = '';
private static $instance;
private function __construct () {
$this->dbh = new PDO(self::$dsn, self::$user, self::$pass);
}
public static function getInstance(){
if(!isset(self::$instance)){
$object = __CLASS__;
self::$instance = new $object;
}
return self::$instance;
}
public function selectQuery($sql, $time = 0) {
$key = md5('query'.$sql);
if(($data = apc_fetch($key)) === false) {
$stmt = $this->dbh->query($sql);
$data = $stmt->fetchAll();
apc_store($key, $data, $time);
}
return $data;
}
}
缓存
class cache{
var url;
public function startFullCache(){
$this->url = 'cache/'.md5($_SERVER['PHP_SELF'].$_SERVER['QUERY_STRING']);
if((@filesize($this->url) > 1) && (time() - filectime($this->url)) < (60 * 15)){
readfile($this->url);
exit;
}
ob_start();
return $this->url;
}
public function endFullCache($cacheUrl){
$output = ob_get_contents();
ob_end_clean();
$output = sanitize_output($output);
file_put_contents($cacheUrl, $output);
echo $output;
flush();
}
}
看法
<html>
<head>
<title><?=$threadTitle[0]?> Thread - Website</title>
</head>
<body>
<h1><?=$threadTitle[0]?> Thread</h1>
</body>
</html>