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

Putting the pieces together - PHP

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




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


Template file '.$templateFile.' not found');



    function parseTemplate($tags,$cacheFile){

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






          else {

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



    function parseFile($file){





          return $content;


    function writeCache($cacheFile,$content){





    function readCache($cacheFile,$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:



// include template parser class


// define class parameters

$tags=array('title'=>'Template System','header'=>'header.php','navbar'=>

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

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: