Does the below code show an acceptable way to cache both fully built pages and database queries?
The caching of built pages is started with the __construct
in the controller and then finished with the __destruct
, in this example all pages are cached for a default of 15 minutes to a file.
The query caching is done with apc
and they are stored in memory for the specified amount of time per query. In the actual site there would be another class for the apc cache so that it could be changed if required.
My aim was to build the most simple possible mvc, have I failed or am I on the right sort of track?
Controller
//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';
}
}
Model
class thread extends model{
public function getTitle($threadId){
$core = Connect::getInstance();
$data = $core->dbh->selectQuery("SELECT title FROM table WHERE id = 1");
return $data;
}
}
Database
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;
}
}
Cache
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();
}
}
View
<html>
<head>
<title><?=$threadTitle[0]?> Thread - Website</title>
</head>
<body>
<h1><?=$threadTitle[0]?> Thread</h1>
</body>
</html>