<?php
class Prison {
var $values=array();
public function __construct($path,$vars) {
foreach($vars as $k=>$v){
$$k = $v;
}
include($path);
}
}
class Template {
var $variables= array();
var $cache_dir;
var $dir;
public function __construct($dir='template/',$cache_dir='cache/') {
$this->cache_dir=$cache_dir;
$this->dir=$dir;
}
/*--------------------------------------PUBLIC--------------------------------------*/
public function is_cached($name,$time=0,$hash='') {
$cache=md5($name.$hash);
if(file_exists($this->cache_dir.$cache) && ($time==-1 || (filemtime($this->cache_dir.$cache)+$time)>time())) {
return true;
} else {
return false;
}
}
public function fetch($name,$time=0,$hash='') {
ob_start();
$cache=md5($name.$hash);
if(file_exists($this->cache_dir.$cache) && ($time==-1 || (filemtime($this->cache_dir.$cache)+$time)>time())) {
include($this->cache_dir.$cache);
} else {
if(!$time) {
error_reporting(E_ERROR && E_WARNING);
new Prison($this->dir.$name,$this->variables);
}
if((!file_exists($this->cache_dir.$cache) || (filemtime($this->cache_dir.$cache)+$time)<=time()) && $time) {
error_reporting(E_ERROR && E_WARNING);
new Prison($this->dir.$name,$this->variables);
$this->cache($cache,$time);
}
}
$text = ob_get_contents();
ob_end_clean();
$this->clear_vars();
return $text;
}
public function assign($name,$value) {
$this->variables[$name] = $value;
}
public function clear_vars() {
$this->variables=array();
}
public function print_vars() {
foreach($this->variables as $k=>$v){
echo "Variable [".$k."] = [";
var_dump($v);
echo "]<br/>";
}
}
/*--------------------------------------PRIVATE--------------------------------------*/
private function cache($cache,$time) {
if(!file_exists($this->cache_dir.$cache)) {
if(file_exists($this->cache_dir.$cache.'.lock')) return 0;
$lock=fopen($this->cache_dir.$cache.'.lock',"w");
@$fp=fopen($this->cache_dir.$cache,"w");
if($fp) {
fputs($fp,ob_get_contents());
fclose($fp);
}
fclose($lock);
unlink($this->cache_dir.$cache.'.lock');
}
if(file_exists($this->cache_dir.$cache) && (filemtime($this->cache_dir.$cache)+$time)<=time()) {
if(file_exists($this->cache_dir.$cache.'.lock')) return 0;
$lock=fopen($this->cache_dir.$cache.'.lock',"w");
unlink($this->cache_dir.$cache);
@$fp=fopen($this->cache_dir.$cache,"w");
if($fp) {
fputs($fp,ob_get_contents());
fclose($fp);
}
fclose($lock);
unlink($this->cache_dir.$cache.'.lock');
}
}
}