PHP
  Home arrow PHP arrow Page 3 - 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? 
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 - Defining the structure of the PHP class
    ( Page 3 of 5 )

     

    Despite the fact that PHP4 doesn’t offer a full-featured object-oriented programming model, with a bit of good will it’s quite possible to create classes and manipulate them in a decent way for the purposes of any project. Fortunately, with the release of PHP5, Object Oriented Programming has been greatly enhanced, introducing object-oriented features such as destructors, exception handling, true public and private methods and properties, and so on.

     

    Regarding our class, we’re going to create it in PHP4, but it may be easily adapted to work seamlessly in PHP5. Let’s not waste more time in preliminaries and set up the class’ basics. Here’s the initial definition:

     

    <?php

    class templateParser {

        

        // member definition

     

        var $output;

     

        function templateParser(){

     

        // constructor setting up class initialization

        }

     

        function parseTemplate(){

     

        // code for parsing template files

        }

     

        function display(){

     

        // code for displaying the finished parsed page

        }

     

    }

    ?>

     

    As can be deduced from the listed code, the class will expose three main methods for parsing template files (including the constructor). Please notice that I’ve defined the class property "$output", which will store the code for the parsed page as it’s being generated. That’s the only property that we need. For now, the class is very simple.

     

    The constructor will accept one parameter, the template file to be parsed. Therefore, before we go deeper into the template parser class code, it’s necessary to have a template file for processing.

     

    I’ve chosen a typical three-column design, with a "header", "navbar", left and right columns, and "footer" sections. Also I decided to delimit the placeholders using braces, since they’re seemingly the most common characters used in template files; hopefully, they allow more compatibility with other possible template systems. Having defined the general guidelines, the template file would look similar to this:

     

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html>

    <head>

    <title>{title}</title>

    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

    <link rel="stylesheet" type="text/css" href="style.css" />

    </head>

    <body>

    <div id="header">{header}</div>

    <div id="navbar">{navbar}</div>

    <div id="leftcol">{leftcontent}</div>

    <div id="content">{maincontent}</div>

    <div id="rightcol">{rightcontent}</div>

    <div id="footer">{footer}</div>

    </body>

    </html>

     

    As you can see, the template is extremely simplistic. However, keep in mind that each placeholder might be replaced with more complex structures, either from static or dynamic files. Now we’re moving forward. Since we’ve already defined the template file, let’s add some functionality to the class constructor, which takes the template file as the unique parameter:

     

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

     

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

     

    }

     

    Let’s explain the tasks performed by the constructor. First, the method checks for the existence of the template file passed as parameter. If the file is found, it grabs the file contents using the "file_get_contents()" PHP built-in function, assigning them to the private variable (in fact it’s a property) $output. Since sometimes is useful to specify default values for incoming parameters, I’ve assigned a default file for the template file. In this case, the default template file is "default_template.htm", but it might be overridden, only passing the name of the other file to the constructor. If no template file is found, I stop the script from executing, displaying an error message to the user.

     

    Now, the best part is coming up. It’s time to have a look at the "parseTemplate()" method, which is the main engine of the class. Let’s define it in the following manner:

     

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

      }

    }

     

    The method accepts an incoming array as a parameter, which stores the data to be inserted into the template placeholders. In this case, I’ve specified again a default "$tag" array, for passing data. Then, the method checks to verify whether the incoming "$tags" array is not empty. If it is not, it iterates over each array element, checking whether the value is a file. If the value corresponds to a file, the method calls the "parseFile()" private method, that, as the name suggest, will parse any file passed as an argument, including files with dynamic content, returning the file contents and assigning them to the local variable $data.

     

    Don’t worry; we’ll see this method in detail in a moment. Let’s go back to the current method. If the value is not a file, it’s directly assigned to the $data variable. Next, the placeholder replacement operation is performed over that $data variable, substituting the placeholders with the proper values, and finally assigning the result to $output. Don’t forget that inside the class we’re referencing any property or method belonging to that class with the prefix "$this".

     

    As you can appreciate, this last section is the workhorse of the method, since it’s where the placeholders’ replacement really occurs. If no valid array parameters are supplied, then I kill the script with the usual die statement, displaying a message that indicates the error. I’m sure the code is pretty easy to follow.

     

    Well, I feel a little more comfortable now, having explained the "parseTemplate()" method, because it’s really the main performer of the class. There are still a couple of methods to explain. So, let’s move on and take a look at them.

     



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

       

    PHP ARTICLES

    - 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
    - Method Chaining: Adding More Methods to the ...
    - Method Chaining in PHP 5
    - The Role of Interfaces in Applying the Depen...
    - Dependency Injection: Using a Setter Method ...
    - Using a Model Class with the Dependency Inje...
    - Injecting Objects Using Setter Methods with ...
    - Injecting Objects by Constructor with the De...
    - The Dependency Injection Design Pattern in P...
    - Performing Inferential Statistical Analysis ...
    - Performing Descriptive Statistical Analysis ...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 Hosted by Hostway
    Stay green...Green IT