PHP
  Home arrow PHP arrow Page 5 - Developing an Extensible Template Proc...
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 
Moblin 
JMSL Numerical Library 
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

Developing an Extensible Template Processor in PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 8
    2006-05-02

    Table of Contents:
  • Developing an Extensible Template Processor in PHP 5
  • Getting started: defining the basic structure of the template processor
  • Assembling the template system: coding the "TemplateProcessor" class
  • Coding the workhorse of the class: defining the "processTemplate()" method
  • Getting the "TemplateProcessor" class completed: defining the remaining class methods

  • 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


    Developing an Extensible Template Processor in PHP 5 - Getting the "TemplateProcessor" class completed: defining the remaining class methods


    (Page 5 of 5 )

    Having explained in detail the way the "processTemplate()" method does its thing, the remaining methods are much more comprehensible. So relax and have a look at the private "readCache()" and "writeCache()" methods, which not surprisingly read from and save the web page to the cache file, after parsing the template file in question:

    private function writeCache(){
        if(!$fp=fopen($this->cacheFile,'w')){
            throw new Exception('Error writing data to cache file');
        }
        fwrite($fp,$this->getCompressedHTML());
        fclose($fp);
    }
    private function readCache(){
        if(!$cacheContents=file_get_contents($this->cacheFile)){
            throw new Exception('Error reading data from cache
    file');
        }
        return $cacheContents;
    }

    As illustrated above, these two methods are invoked internally by the class, in order to read and write respectively the parsed web page. Also, notice that the entire read-write sequence is performed on compressed page contents, since the first time (and certainly the subsequent ones) that contents are saved to the cache file, the class encodes the data by calling the "getCompressedHTML()" method.

    By the way, now that I mentioned this method, below you can see its signature:

    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;
    }

    What this method does essentially is use "Gzip" encoding for compressing the parsed web page, which is fetched either from the cache file, or after being parsed at runtime. In this method, I used the PHP built-in "gzencode()" function, in order to encode the whole web page and return the compressed contents to calling code. Additionally, new line characters are removed from the page, something that can be effective for reducing the size of the parsed web document.

    Fine, there's still a couple of simple methods that you need to learn, in order to complete the "TemplateProcessor" class. Below, there are the definitions of the "getHTML()" and "sendEncodingHeader()" methods, respectively:

    public function getHTML(){
        return $this->output;
    }

    public function sendEncodingHeader(){
        header('Content-Encoding: gzip');
    }

    These two methods are really simple ones. The first returns the whole (X)HTML output to calling code, after parsing the template file and replacing placeholders with real data. The second method is responsible for sending the proper "Content-Encoding: gzip" http header, in order to allow the transference of encoded data.

    Okay, the two methods shown above finally complete the definition of the "TemplateProcessor" class. Considering that you may want to see how the entire class looks, I listed its full source code below:

    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=3600;// 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');
        }
    }

    That's the full source code of my "TemplateProcessor" class. Now that I assembled all the previous methods within the class structure, you can see how each piece of code fits with each other piece. However, if you want to test (and tweak) the class, you can download a sample ZIP file, which contains all the supporting files required to get the class working. You can use this link or the one at the beginning of the article.

    Bottom line

    That's all for the moment. Over this first article I went through the development of an extensible template processing class in PHP 5 that exposes some interesting features, such as recursive placeholders replacement, processing of PHP files and MySQL datasets, and so forth.

    In the next part of the series, I'll set up a step-by-step example that will show you how to use the "TemplateProcessor" class with different input tags. See you in the next part!


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · In this first article, you'll learn how to build the structure of the template...
     

       

    PHP ARTICLES

    - Validating Web Forms with the Code Igniter P...
    - Output Buffering
    - Paginating Database Records with the Code Ig...
    - HTTP Headers in Web Development
    - Project Management: Administration
    - Building a Database-Driven Application with ...
    - User Authentication for a Project Management...
    - Introduction to the CodeIgniter PHP Framework
    - Adding Users for a Project Management Applic...
    - Migrating Class Code for a MIME Email to PHP...
    - Login and Logout Authentication for a Projec...
    - Composing Messages in HTML for MIME Email wi...
    - Project Management: Authentication
    - A Better Way to Determine MIME Types for MIM...
    - Project Management Overview





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