Home arrow PHP arrow Page 5 - Building a Template Parser Class with PHP, Part I

Implementing the class - PHP

It is easy to create a templating system in PHP; in fact, there are a number of templating system packages. But what if you're putting together a relatively small website, and don't really need one of those full-fledged systems? In this first part of a two-part article, you will learn how to create a simple but extensible PHP class for parsing templates.

TABLE OF CONTENTS:
  1. Building a Template Parser Class with PHP, Part I
  2. PHP: The first templating system available
  3. Defining the structure of the PHP class
  4. Completing the class: the "parseFile()" and "display()" methods
  5. Implementing the class
By: Alejandro Gervasio
Rating: starstarstarstarstar / 85
March 22, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

 

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
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

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