Home arrow PHP arrow 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.

TABLE OF CONTENTS:
  1. Using a Template Processor Class in PHP 5
  2. Getting started using the “TemplateProcessor” class: a quick look at its definition
  3. Parsing template files: defining the input tags for the “TemplateProcessor” class
  4. Going one step further: seeing the “TemplateProcessor” class in action
By: Alejandro Gervasio
Rating: starstarstarstarstar / 4
May 09, 2006

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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.='&nbsp;'.$col.'&nbsp;';
                    }
                    $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.



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: