HomePHP Page 2 - Using a Template Processor Class in PHP 5
Getting started using the “TemplateProcessor” class: a quick look at its definition - PHP
Welcome to part two of the series “Separating logic from presentation.” Comprised of three articles, this series walks you through the development of an extensible template processor in PHP 5, which you might find quite useful for separating the logic of your PHP applications from their visual presentation.
Before I proceed to demonstrate how to use the “TemplateProcessor” class, I need to remind you of how it looks, so it can be fresh in your mind. That said, here’s the corresponding definition for the class, as I wrote it originally in the first article:
// define 'TemplateProcessor' class class TemplateProcessor { private $output='';// set default value for general class output private $rowTag='p';// set default value for database row tag private $tags=array();// set default value for tags private $templateFile='default_template.htm';// set default value for template file private $cacheFile='default_cache.txt';// set default value for cache file private $expiry=10;// set default value for cache expiration public function __construct($tags=array()){ if(count($tags)<1){ throw new Exception('Invalid number of tags'); } if($this->isCacheValid()){ // read data from cache file $this->output=$this->readCache(); } else{ $this->tags=$tags; // read template file $this->output=file_get_contents($this->templateFile); // process template file $this->processTemplate($this->tags); // clean up empty tags $this->output=preg_replace("/{w}|}/",'',$this- >output); // write compressed data to cache file $this->writeCache(); } // send gzip encoding http header $this->sendEncodingHeader(); } // check cache validity private function isCacheValid(){ // determine if cache file is valid or not if(file_exists($this->cacheFile)&&filemtime($this- >cacheFile)>(time()-$this->expiry)){ return true; } return false; } // process template file private function processTemplate($tags){ foreach($tags as $tag=>$data){ // if data is array, traverse recursive array of tags if(is_array($data)){ $this->output=preg_replace("/{$tag/",'',$this- >output); $this->processTemplate($data); } // if data is a file, fetch processed file elseif(file_exists($data)){ $data=$this->processFile($data); } // if data is a MySQL result set, obtain a formatted list of database rows elseif(@get_resource_type($data)=='mysql result'){ $rows=''; while($row=mysql_fetch_row($data)){ $cols=''; foreach($row as $col){ $cols.=' '.$col.' '; } $rows.='<'.$this- >rowTag.'>'.$cols.'</'.$this->rowTag.'>'; } $data=$rows; } // if data contains the '[code]' elimiter, parse data as PHP code elseif(substr($data,0,6)=='[code]'){ $data=eval(substr($data,6)); } $this->output=str_replace('{'.$tag.'}',$data,$this- >output); } } // process input file private function processFile($file){ ob_start(); include($file); $contents=ob_get_contents(); ob_end_clean(); return $contents; } // write compressed data to cache file private function writeCache(){ if(!$fp=fopen($this->cacheFile,'w')){ throw new Exception('Error writing data to cache file'); } fwrite($fp,$this->getCompressedHTML()); fclose($fp); } // read compressed data from cache file private function readCache(){ if(!$cacheContents=file_get_contents($this->cacheFile)){ throw new Exception('Error reading data from cache file'); } return $cacheContents; } // return overall output public function getHTML(){ return $this->output; } // return compressed output private function getCompressedHTML(){ // check if browser supports gzip encoding if(strstr($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip')){ // start output buffer ob_start(); // echo page contents to output buffer echo $this->output; // crunch (X)HTML content & compress it with gzip $this->output=gzencode(preg_replace("/ (rn|n)/","",ob_get_contents()),9); // clean up output buffer ob_end_clean(); // return compressed (X)HTML content return $this->output; } return false; } // send gzip encoding http header public function sendEncodingHeader(){ header('Content-Encoding: gzip'); } }
I suppose at this point, after listing the “TemplateProcessor” class, you’re ready to see an illustrative hands-on example, in order to learn how you can use it for parsing your template files. Want to learn how this will be achieved? Please, read the next few lines.