HomePHP Page 4 - Building a Template Parser Class with PHP, Part I
Completing the class: the "parseFile()" and "display()" methods - 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.
We have the class still in an incomplete state. As I stated before, the "parseTemplate()" method calls internally to "parseFile()". Why did I decide to implement this method? The reason for its existence is simple. I want the class to parse any kind of files either with static or dynamic content.
Let us suppose that we’re generating the content section of the page, including some dynamic data such as date information or PHP variables populated with database records. The need to process files with dynamic information becomes evident, expanding the class’ capabilities. Let’s look at the corresponding code for this method. Its definition is the following:
function parseFile($file){
ob_start();
include($file);
$content=ob_get_contents();
ob_end_clean();
return $content;
}
In order to parse files with dynamic data, the method starts an output buffer, includes the file and retrieves the file contents from the buffer. Next, it clears up the buffer and returns the data. That’s simple and straightforward, right?
At this point, the class is capable of parsing template files, replacing the placeholders with static or dynamic information and generating the page. What more can we ask for? Of course, we still need to display the corresponding content for the page generated. So, let’s define the last method of the class, the "display()" method:
function display(){
return $this->output;
}
Whew, I'm sure you’re completely overwhelmed by the code listed above. Just kidding. In fact, it’s all we need to define the method. It simply returns the contents of the page generated after the replacement operation.
You may be wondering why I am not displaying directly the page, instead of returning its contents? Generally it’s a bad idea to display contents inside the class, because we might need to do something different with the data (i.e. send it via email). That’s why the method returns the page instead of displaying it directly in the browser.
The class is now finished and ready to be implemented in any project. It’s time to put the class into action.