PHP
  Home arrow PHP arrow Page 5 - Building a Template Parser Class with PHP, Part I
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 I
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 73
    2005-03-22


    Table of Contents:
  • Building a Template Parser Class with PHP, Part I
  • PHP: The first templating system available
  • Defining the structure of the PHP class
  • Completing the class: the "parseFile()" and "display()" methods
  • Implementing the class

  • 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 I - Implementing the class
    ( Page 5 of 5 )

     

    Before we see how the class is practically implemented, let’s see the complete source code. Here’s the listing:

     

    class templateParser {

        var $output;

        function templateParser($templateFile='default_template.htm'){

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

        }

        function parseTemplate($tags=array()){

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

                   }

              }

              else {

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

              }

        }

        function parseFile($file){

              ob_start();

              include($file);

              $content=ob_get_contents();

              ob_end_clean();

              return $content;

        }

        function display(){

              return $this->output;

        }

    }

     

    Finally, here’s a possible real implementation for the class:

     

    <?php

    // include the class

    require_once('template.php');

    // instantiate a new template Parser object

    $tp=&new templateParser('template.htm');

    // define parameters for the class

    $tags=array('title'=>'You are seeing the template parser class in action!','header'=>'header.php','navbar'=>
    'navigation bar.php','leftcontent'=>'leftcontent.php',
    'maincontent'=>'maincontent.php',
    'rightcontent'=>'rightcontent.php',
    'footer'=>'footer.php');

    // parse template file

    $tp->parseTemplate($tags);

    // display generated page

    echo $tp->display();

    ?>

     

    The above code is really easy to follow. First, I include the proper class file. Then a new template parser object is instantiated, specifying a "template.htm" file as the template to be parsed.

     

    Please note that I’m instantiating the object with the (&) ampersand operator, which means that I’m working with a reference of the object, not a copy. This is necessary in PHP4 for specifying the behavior when we’re instantiating objects. Fortunately, in PHP 5, the default behavior is working with object references.

     

    Next, I define an array structure containing the parameters to be passed to the class. In the example, I’ve chosen a string for page title, and several PHP files for generating the different sections of the page. As you can see, the class offers the possibility to include dynamic or regular content. 

     

    Finally, the object invokes the "parseTemplate()" method, which will replace the placeholders with the real values contained in the "$tags" array. Once the template is processed, the "display()" method is called, displaying the generated page. Here, it becomes clear that instead of directly echoing page contents, we might, for instance, send the page via email. Doing so makes the class much more flexible.

     

    Summary

     

    Are you still with me? Okay, we have finally created a simple but extensible class for parsing template files with no major headaches. What’s more, the code is easily portable to PHP 5 with minor modifications. However, the job is not completely done. In the second part of this article, I’ll add some caching capabilities to the original class, increasing its current functionality. In the meantime, feel free to play around with the code and think about possible improvements. I'll meet you in the second part!  



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

       

    PHP ARTICLES

    - 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...
    - Mastering WHILE Loops for PHP and MySQL





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