PHP
  Home arrow PHP arrow Building a Template Parser Class with ...
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 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
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 II
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 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:
      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


    Building a Template Parser Class with PHP, Part II


    (Page 1 of 3 )

    In part one of this two part article series, you learned how to build a simple template parser class in PHP. In this second article, you will learn how to add caching capabilities to the class.

     

    Introduction

     

    Welcome to the second part of the article "Building a Template Parser class with PHP." In the first part of the article, I’ve hopefully demonstrated that building a simple template parser class is not as intimidating as it seems. Given the flexibility and power that PHP offers, it’s possible to implement efficient applications without scratching our heads.

     

    Since the original version of the class was quite simple, I felt strongly tempted to expand it, adding a little more functionality. So, I thought that incorporating caching capabilities to the class, without incurring time-consuming processes, was worth considering. In this second part, I’m going to show how to improve the original class, by adding a simple caching mechanism, with little modifications. So, let’s get started. 

     

    Refreshing memories: a quick look at the original class

     

    Before we get into the process of tweaking the class code a bit, it would be good to remind ourselves how the original version looked, in order to establish a starting point for implementing the new caching capabilities. Here’s the full code for the template parser class:

     

    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;

        }

    }

     

    Since we’re talking about a template class, there must be a template file for proper processing. Therefore, let’s show the code for the template file used, as it was originally conceived:

     

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.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>

     

    Now, things are beginning to make sense, and I can briefly explain the underlying logic of the class. To begin with, the class constructor accepts the template file as the only parameter for being processed. After checking whether the file really exists, it simply assigns the file contents to the $output variable, which is storing the page, as it’s being generated. Then, the workhorse method of the class, that is, "parseTemplate()", takes the incoming $tags array for replacing all of the placeholders present in the template file, along with the corresponding data, stored in the mentioned $tags array. Doing so, the placeholders {header}, {navbar}, {leftcontent}, and so forth, will be substituted will real data, coming from regular variables or files.

     

    As you can see, the method is calling internally to "parseFile()," which takes care of retrieving the contents from any file that might be included as part of the $tags array, parsing static or dynamic content. This is extremely handy for processing data from PHP variables, including any kind of dynamic information. Stick with me, because the explanation is almost done.

     

    Once the "parseTemplate()" method has performed the replacement process, the remaining task is a breeze. The class exposes the "display()" method for getting the finished version of the page, which is stored in the $output variable, to be displayed in the browser, or processed in another way, according to the application’s needs.

     

    Well, maybe this is not shocking news, but if we feed the class with a correct template file, we obtain a finished page populated with the corresponding data. This is a simple and effective way to give websites a consistent look with no big hassles. The final class implementation might be something similar to this:

     

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

    ?>

     

    Okay, if you read the first part of this article, the above code is pretty familiar, but for those just coming in for this sequel, the previous explanation was well spent. Now, having briefly explained the core logic behind the class, let’s get ready to add a pinch of caching capabilities. Just keep reading to find out more.

     

    More PHP Articles
    More By Alejandro Gervasio


       · In this second part, the class is expanded to add a basic caching mechanism.Since...
       · Only for aclaration, there is a typo. Where it says witeCache(), should read...
       · We fixed the error, thank you for pointing it out.
       · You're very welcome:-)Thank you.
       · Thanks for the great article! As someone pointed out in the comments for Part 1 of...
       · I was hoping that in Part II you might discuss a strategy to parse tags recursively,...
       · This class really rocks. I will use it for sure. Thanks man.I simply hate...
       · Thank you for the comments.Well, Reagarding your question about dealing with...
       · Hey, thank you for the kind words about the class. Regarding your opinion about...
       · Thanks for the comments.There are several ways to expand the class and add more...
       · I have used Smarty exclusively for the past half dozen projects I have been involved...
       · Thanks a lot for the comments about the class. If this application has been a source...
       · I agree with you and with the author. Smarty has it's place for sure. I also use...
       · Hey, I'm glad you liked the class and I really appreciate your words.With no doubt...
       · It would be great to see another part to this!Way to go on I and II.
       · I'll see if I can give a try writing Part III soon.Thank you.
       · Good article on using a template, but I have a question. I'm doing a similar thing,...
       · Thank you for the kind words about the article. Regarding your question, the answer...
       · I'm a bit confused on how this gets implemented. I see three possible PHP/HTML...
       · There are several ways to generate multiple pages using a template file. With a...
       · I've experienced an issue with this class that I'm not sure how to truly resolve. ...
       · I think that your problem is rather easy to solve. Here's a possible solution:In...
       · hi,I'd like to start out by saying what great articles you've made. I've been...
       · Hi friend,Thank you for the compliments. They're really important.Regarding...
       · Hmm, I think I see what you're saying. It's a different approach than I was taking...
       · If you want to keep in your template file as much HTML markup as possible, just...
       · Not that I condone script errors, but just curious how you would prevent error...
       · Hello,About your question, I'll try to give you a general answer, since error...
       · Hey That would be nice part of the class in article 3!
       · Yes, the subject might be covered on a third part. However, I think that all of the...
       · Nice atricles. When I try to use te cache version there is a problem with write...
       · when will be the released of your part III>>>
       · based on"With this single load.php file you'll generate all of your website pages....
       · Thank you for commenting on my PHP article. Now, when all the pages are built from...
     

       

    PHP ARTICLES

    - Authentication Scripts for a User Management...
    - Utilizing the Use Keyword for Namespaces in ...
    - Building a User Management Application
    - Working With Different Namespaces in PHP 5
    - User Management Explained: Overview
    - Using Namespaces in PHP 5
    - Database Security: Guarding Against SQL Inje...
    - Building a Modular Exception Class in PHP 5
    - Database and Password Security for Web Appli...
    - Handling MySQL Data Set Failures in PHP 5
    - Building Site Registration for Web Applicati...
    - Intercepting Customized Exceptions in PHP 5
    - Securing Your Web Application Against Attacks
    - Sub Classing Exceptions in PHP 5
    - Authentication for Web Application Security





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