HomePHP Building a Template Parser Class with PHP, Part I
Building a Template Parser Class with PHP, Part I
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.
Without a doubt, PHP is one of the most popular languages currently available for fast Web development. Its extreme ease and flexibility has made it a great source for creating a wide gamut of applications, well suited for satisfying the needs of different projects. Certainly, one of the most common applications that have grown noticeably in popularity is what is widely know as a templating system.
The question is: what is a templating system? Well, in short terms, itís an easy way to create large sites with some effort to maintain a consistent appearance through the different documents. Just by having only one template file, which stores the HTML markup and the data placeholders, we are able to manipulate it with a PHP script that takes the template file and replaces those placeholders with the corresponding content, in order to generate the final version of the page. The concept behind templating is very handy, since it allows us to separate the markup and visual presentation from the logic of the application in different layers.
As a PHP programmer, you probably have used some of the most popular template system packages, including the powerful Smarty, or other solutions such as Fast Template or Pat Template among others (add your own to the list). Most of these packages are full-featured and mature solutions designed to be generally implemented on medium and large size projects. They present numerous options that sometimes are pretty cumbersome, particularly when dealing with small projects, where templating needs are rather basic.
Okay, right now I can hear some well-intended programmers complaining about this, arguing that those packages can be perfectly implemented for the tiny lovely pet website of Uncle Johnny, including a huge Microsoft SQL Server database system, and so on. You get the idea. But, letís be honest. For small applications we need a simple templating system that nicely fits our needs.
Because of the reasons I mentioned above, I decided to write on my own a simple but extensible PHP class for parsing templates. I designed it to satisfy the minor requirements of small websites. Fine, are you ready to put our hands on the code? Just follow me. Weíre involved in this situation together!