Home arrow PHP arrow Building a Template Parser Class with PHP, Part II

Building a Template Parser Class with PHP, Part II

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.

  1. Building a Template Parser Class with PHP, Part II
  2. One step forward: defining caching methods
  3. Putting the pieces together
By: Alejandro Gervasio
Rating: starstarstarstarstar / 28
March 29, 2005

print this article






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

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


    function parseTemplate($tags=array()){


               foreach($tags as $tag=>$data){





          else {

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



    function parseFile($file){





          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">




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

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



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




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:



// include the class


// 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

// parse template file


// 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

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: