SunQuest
 
       PHP
  Home arrow PHP arrow Page 2 - Using a Template Processor Class in PH...
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Actuate Whitepapers 
Moblin 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Using a Template Processor Class in PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 4
    2006-05-09

    Table of Contents:
  • Using a Template Processor Class in PHP 5
  • Getting started using the “TemplateProcessor” class: a quick look at its definition
  • Parsing template files: defining the input tags for the “TemplateProcessor” class
  • Going one step further: seeing the “TemplateProcessor” class in action

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    Using a Template Processor Class in PHP 5 - Getting started using the “TemplateProcessor” class: a quick look at its definition


    (Page 2 of 4 )

    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


       · In this tutorial, the template processor I developed during the previous article is...
       · Hi Alejandro,I have read many of your articles and have found all of them an...
       · Hi there,Thank you for your comments on my PHP article, as well as your kind...
       · Alejandro, That one doesn't work either?? I know practically nothing about regular...
       · Hello again,Sorry to hear about the syntax error again, but I used the class...
       · I got the same syntax error above - and like many find regular expressions rather...
       · 2 with reference to the above error - the problem is not in the regular expression...
       · First off, I'd like to thank you for commenting on my PHP article. And lastly, with...
       · just another note, the compressed html regex needs to escape for the line breaks...
       · Thank you for posting some improvements on the template parser class, since they're...
       · i tried the suggestion but it did not work so i edited it to (\r\n|\n) and it...
       · Thanks alejandro for the wonderful code, it took me a whole night of anylizing where...
       · Thank you for commenting on my PHP article. I see you modified the source code of...
       · Thank you for commenting on my PHP article. The correct regexp is the one you used,...
     

       

    PHP ARTICLES

    - Handling Attachments in MIME Email with PHP
    - Completing the Project Management Application
    - Sending MIME Email with PHP
    - Handling Files for a Project Management Appl...
    - Viewing and Editing Tasks for a Project Mana...
    - More on Private Methods with PHP 5 Member Vi...
    - Adding Tasks to a Project Management Applica...
    - Utilizing Private Methods with PHP 5 and Mem...
    - Making Changes in a Project Management Appli...
    - Defining Public and Protected Methods with M...
    - HTML for a Project Management Application
    - Using Subclasses and Accessors with Member V...
    - Implementing Internet Protocols with PHP
    - Project Management: The Application
    - Working with Private Properties to Protect P...




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway