<?php if(!defined("BASE")){ die("Direct access not allowed."); }
class Template{
private $tags = array();
private $cacheLifeTime;
private $cacheMod;
private $cacheDir = "cache";
private $viewDir = "tmpl";
private $cacheKey;
public function Display($view_name){
$pathtofile = $this->cacheDir."/".md5($this->cacheKey)."/".$view_name.".php";
if(!file_exists($this->viewDir."/".$view_name.".tpl")){
die("Failed to compile template: ".$view_name." not exists");
}else{
if($this->cacheMod == true){
if($this->isCached($view_name)){
include_once($this->cacheDir."/".md5($this->cacheKey)."/".$view_name.".php");
}else{
if(!is_dir($this->cacheDir."/".md5($this->cacheKey))){
mkdir($this->cacheDir."/".md5($this->cacheKey), 0, true);
}
$output = file_get_contents($this->viewDir."/".$view_name.".tpl");
if(count($this->tags) > 0){
foreach($this->tags as $key => $value){
$output = str_replace('{'.$key.'}', $value, $output);
}
}
$fp = fopen($this->cacheDir."/".md5($this->cacheKey)."/".$view_name.".php", "w+");
fwrite($fp, $output);
fclose($fp);
include_once($this->cacheDir."/".md5($this->cacheKey)."/".$view_name.".php");
}
}else{
$output = file_get_contents($this->viewDir."/".$view_name.".tpl");
if(count($this->tags) > 0){
foreach($this->tags as $key => $value){
$output = str_replace('{'.$key.'}', $value, $output);
}
}
echo $output;
}
}
}
public function setVars($tag, $value){
if(is_array($tag) && is_array($value)){
foreach(array_combine($tag, $value) as $key => $value){
$this->tags[$key] = $value;
}
}elseif(!is_array($tag) && is_array($value) || is_array($tag) && !is_array($value)){
die("Failed to compile template: Tag or Value not array.");
}elseif(!is_array($tag) && !is_array($value)){
$this->tags[$tag] = $value;
}
}
public function setCacheMod($trueorfalse){
if(!is_bool($trueorfalse)){
$this->cacheMod = false;
}else{
$this->cacheMod = $trueorfalse;
}
}
public function setCacheLifeTime($seconds){
if(!is_numeric($seconds)){
$this->cacheLifeTime = 0;
}else{
$this->cacheLifeTime = round($seconds);
}
}
public function setCacheKey($key){
$this->cacheKey = $key;
}
private function isCached($view_name){
$pathtofile = $this->cacheDir."/".md5($this->cacheKey)."/".$view_name.".php";
if(file_exists($pathtofile)){
if(filemtime($pathtofile) > (time() - $this->cacheLifeTime)){
return true;
}else{
unlink($pathtofile);
return false;
}
}
}
}
?>