HomePHP Page 2 - Building a Template Parser Class with PHP, Part I
PHP: The first templating system available - 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.
<p>The author of this song is: <?php echo $author?></p>
The above example shows us that PHP is itself a templating system. Of course, this approach is not recommended for many reasons. Here we’re mixing up PHP code with HTML markup, which you do not want to do if your goal is to keep applications in different layers.
To improve the situation and maintain applications in separated layers, we might define our template in the following way:
And next, the PHP code to replace the variables with the corresponding values:
// lets's define some variables
$title='This page is pretty musical';
$content='There are unsmiling faces and bright plastic chains, and a wheel in perpetual motion.';
$author='The Alan Parsons Project.';
// now let's replace their values in the document
// parse the template to replace variables with their values
// send parsed file to the browser
As you can see, the situation is much more acceptable. We have a single HTML template file, where we’ve defined some variables as placeholders. Then, starting an output buffer, we grab the content of the included template file, escaping any characters that would break a PHP string, and finally dumping it to a variable. Using "eval()" we evaluate a string as if it were PHP code. This means that the variables in our template are replaced by the values previously assigned. We’re getting closer to creating a simple template parser, but still the above approach is not good enough. Still, it is a basic technique for parsing template files.
However, we need to have more flexibility at the moment of defining the placeholders, looking for an object-oriented solution. This way our code is more reusable and encapsulated. Taking this into account, we’re going to define a simple PHP template parser class for processing template files and send the finished page to the browser, or wherever you want to submit it. Let’s take a look at the basic structure of the PHP class.