PHP
  Home arrow PHP arrow Page 3 - Building a Template Parser Class with PHP, Part II
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
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? 
Google.com  
PHP

Building a Template Parser Class with PHP, Part II
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 27
    2005-03-29


    Table of Contents:
  • Building a Template Parser Class with PHP, Part II
  • One step forward: defining caching methods
  • Putting the pieces together

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log 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


    Building a Template Parser Class with PHP, Part II - Putting the pieces together
    ( Page 3 of 3 )

     

    Now, things are getting more exciting. Once we’ve defined the corresponding caching methods, the class’ logic is really easy to understand. Take my word for it. Before doing any template file process, the handy class just checks whether there is a valid cache file for retrieving contents. If there is, they are grabbed from the cache file and assigned to the $output variable, avoiding any additional template processing. Otherwise, the class performs the regular template-parsing task, as defined in the original version. Isn’t it sweet and simple?

     

    Indeed, the explanation I just gave would be rather useless without showing the code of the new, caching-improved class. So here’s the complete listing:

     

    class templateParser {

        var $output;

        function templateParser($tags=array
    (),$cacheFile='default_cache.txt',$expireTime=3600,
    $templateFile='default_template.htm'){

              if(!$this->output=$this->readCache
    ($cacheFile,$expireTime)){

                   (file_exists($templateFile))?$this-
    >output=file_get_contents($templateFile):die('Error:
    Template file '.$templateFile.' not found');
                   $this->parseTemplate($tags,$cacheFile);

              }

        }

        function parseTemplate($tags,$cacheFile){

              if(count($tags)>0){
                   foreach($tags as $tag=>$data){

                        $data=(file_exists($data))?$this-
    >parseFile($data):$data;

                       $this->output=str_replace
    ('{'.$tag.'}',$data,$this->output);

                   }

                   $this->writeCache($cacheFile,$this-
    >output);

              }

              else {

                   die('Error: No tags or files were
    provided for replacement');

              }

        }

        function parseFile($file){

              ob_start();

              include($file);

              $content=ob_get_contents();

              ob_end_clean();

              return $content;

        }

        function writeCache($cacheFile,$content){

              $fp=fopen($cacheFile,'w');

              fwrite($fp,$content);

              fclose($fp);

        }

        function readCache($cacheFile,$expireTime){

              if(file_exists($cacheFile)&&filemtime
    ($cacheFile)>(time()-$expireTime)){
                   return file_get_contents($cacheFile);

              }

              return false;

        }

        function display(){

              return $this->output;

        }

    }

     

    From the above code, we can deduct that this new version is similar to the "cache-less" one. But let’s break down the code to understand what it does. First, we notice that the constructor takes four parameters respectively: the $tags array, the cache file, the time expiry and finally, the template file. For all of these arguments I’ve specified default values, in the following sequence: an empty $tag array, "default_cache.txt" for default cache file, a value of 3600 seconds (1 hour) for cache time expiry and finally "default_template.htm" for the template file.

     

    Then, as stated previously, the constructor checks for the existence of a valid cache file, invoking the private "readCache()" method. If a valid cache is found, the cached contents are stored in the $output variable to be returned later from the class. Otherwise, if no valid cache exists (the file doesn’t exists or the time expiry has been reached), the constructor performs the regular template parsing process, as defined in the original version, calling the "parseTemplate()" method.

     

    As you can see, here we’ve moved "parseTemplate()" inside the constructor, turning it into a private method (remember that originally it was defined as public), for being called only if no valid cache file is found. The reason for doing this should become clear, since the class on its own is now capable of determining where to look to retrieve page contents. Regarding the "parseTemplate()" method, the only addition resides in writing the contents of the finished page to the cache file, once the template file has been parsed.

     

    Finally, the "display()" method remains identical to the previous version, this time returning either the contents from the generated page or directly from the cache file. Not too difficult, right?

     

    At this point, we’ve made some minor changes to the original class, adding a couple of simple methods for implementing a basic cache mechanism, based on a time expiration policy. This might be a possible implementation of the class:

     

    <?php

    // include template parser class

    require_once('template.php');

    // define class parameters

    $tags=array('title'=>'Template System','header'=>'header.php','navbar'=>
    'navbar.php','leftcontent'=>
    'leftcontent.php','maincontent'=>'maincontent.php',
    'rightcontent'=>
    'rightcontent.php','footer'=>'footer.php');

    // instantiate a new template parser object specifying a cache file valid for 2 hours

    $tp=&new templateParser($tags,'cache.txt',2*3600,'template.htm');

    // display finished page

    echo $tp->display();

    ?>

     

    Truly, the example is self-explanatory. First, as usual, we include the required class file. Second, we define the values of the $tags array for  processing, specifying page title, and the required files for page generation. I’ve chosen to pass file names, but I could have hard-coded HTML instead. Finally, we instantiate a new object from the class, assigning a cache file valid for two hours (2*3600), and the corresponding template file, in this case, "template.htm." The last statement simply displays the page created, either from the parsed template file or directly from the cache file.

     

    Good! We have a template parsing class that offers basic but effective caching capabilities. Let’s congratulate ourselves. If you ever thought that building such a class was an obscure and painful experience, you were mistaken!

     

    Wrapping up

     

    In this article series, I hope I've demonstrated that building a PHP class for parsing template files and caching generated output is not difficult at all. Also, I hope this encourages PHP programmers wishing to taste the power of Object Oriented Programming with real-world applications. Of course, we must keep in mind that PHP4 doesn’t offer the full features for doing so, but with a little bit of will power, the job can be done decently. If you really want to dig deeper in OOP, while keeping your background in PHP, give PHP5 a try. The new and powerful Object Model will amaze you. The challenge is out there. Just try it out.  



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

       

    PHP ARTICLES

    - Adding Ordering and Grouping Clauses to the ...
    - Implementing Factory Methods in PHP 5
    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek