Hi.
As usual I'm taking my first steps in something 🙂
It's the Output Control time (caching,template,compresion).
Let's get down to the nitty-gritty.
The code:
<?php
class Template
{
private $outPut='';
private $vars=array();
public function __construct($templateFile){
ob_start();
(file_exists($templateFile))?$this->outPut=file_get_contents($templateFile):exit('Error:Template file '.$templateFile.' not found');
}
public function assign($vars){
if (!is_array($vars)){
exit('Error! assign() expects an array, string given');
}
$this->vars=$vars;
}
public function parse(){
foreach ($this->vars as $var => $content){
$this->outPut=str_replace('{'.$var.'}', $content, $this->outPut);
}
echo $this->outPut;
}
public function display(){
$this->outPut=gzencode(ob_get_contents(),9);
ob_end_clean();
header('Content-Encoding: gzip');
return $this->outPut;
}
}
?>
<?php
$tpl = new Template('test.htm');
$tpl->assign(array('path'=>$_SERVER['PHP_SELF'],'time'=>time(),'name'=>'Yasin','submit'=>'Schizza'));
$tpl->parse();
echo $tpl->display();
?>
The trivial test.htm
<form action="{path}" method="post">
<input type="hidden" name="user_time" value="{time}" /><br />
<input type="text" name="user_name" value="{name}" /><br />
<input type="submit" name="submit" value="{submit}">
</form>
I'm wondering is it the right way ?
BTW
In this snippet:
(file_exists($templateFile))?$this->outPut=file_get_contents($templateFile):exit('Error:Template file '.$templateFile.' not found');
if (!is_array($vars)){
exit('Error! assign() expects an array, string given');
}
Is it a good idea to throw an Exception ?
In my opinion to checking a method parameter
is better using exit.
What do you think about ?
Thanks in advance.
Bye