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

Defining the structure of the PHP 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

 

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
 

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: