Building a Template Parser Class with PHP, Part II - Putting the pieces together (
Page 3 of 3 )
Now, things are getting more exciting. Once we’ve defined the corresponding caching methods, the class’ logic is really easy to understand. Take my word for it. Before doing any template file process, the handy class just checks whether there is a valid cache file for retrieving contents. If there is, they are grabbed from the cache file and assigned to the $output variable, avoiding any additional template processing. Otherwise, the class performs the regular template-parsing task, as defined in the original version. Isn’t it sweet and simple?
Indeed, the explanation I just gave would be rather useless without showing the code of the new, caching-improved class. So here’s the complete listing:
class templateParser {
var $output;
function templateParser($tags=array
(),$cacheFile='default_cache.txt',$expireTime=3600,
$templateFile='default_template.htm'){
if(!$this->output=$this->readCache
($cacheFile,$expireTime)){
(file_exists($templateFile))?$this-
>output=file_get_contents($templateFile):die('Error:
Template file '.$templateFile.' not found');
$this->parseTemplate($tags,$cacheFile);
}
}
function parseTemplate($tags,$cacheFile){
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);
}
$this->writeCache($cacheFile,$this-
>output);
}
else {
die('Error: No tags or files were
provided for replacement');
}
}
function parseFile($file){
ob_start();
include($file);
$content=ob_get_contents();
ob_end_clean();
return $content;
}
function writeCache($cacheFile,$content){
$fp=fopen($cacheFile,'w');
fwrite($fp,$content);
fclose($fp);
}
function readCache($cacheFile,$expireTime){
if(file_exists($cacheFile)&&filemtime
($cacheFile)>(time()-$expireTime)){
return file_get_contents($cacheFile);
}
return false;
}
function display(){
return $this->output;
}
}
From the above code, we can deduct that this new version is similar to the "cache-less" one. But let’s break down the code to understand what it does. First, we notice that the constructor takes four parameters respectively: the $tags array, the cache file, the time expiry and finally, the template file. For all of these arguments I’ve specified default values, in the following sequence: an empty $tag array, "default_cache.txt" for default cache file, a value of 3600 seconds (1 hour) for cache time expiry and finally "default_template.htm" for the template file.
Then, as stated previously, the constructor checks for the existence of a valid cache file, invoking the private "readCache()" method. If a valid cache is found, the cached contents are stored in the $output variable to be returned later from the class. Otherwise, if no valid cache exists (the file doesn’t exists or the time expiry has been reached), the constructor performs the regular template parsing process, as defined in the original version, calling the "parseTemplate()" method.
As you can see, here we’ve moved "parseTemplate()" inside the constructor, turning it into a private method (remember that originally it was defined as public), for being called only if no valid cache file is found. The reason for doing this should become clear, since the class on its own is now capable of determining where to look to retrieve page contents. Regarding the "parseTemplate()" method, the only addition resides in writing the contents of the finished page to the cache file, once the template file has been parsed.
Finally, the "display()" method remains identical to the previous version, this time returning either the contents from the generated page or directly from the cache file. Not too difficult, right?
At this point, we’ve made some minor changes to the original class, adding a couple of simple methods for implementing a basic cache mechanism, based on a time expiration policy. This might be a possible implementation of the class:
<?php
// include template parser class
require_once('template.php');
// define class parameters
$tags=array('title'=>'Template System','header'=>'header.php','navbar'=>
'navbar.php','leftcontent'=>
'leftcontent.php','maincontent'=>'maincontent.php',
'rightcontent'=>
'rightcontent.php','footer'=>'footer.php');
// instantiate a new template parser object specifying a cache file valid for 2 hours
$tp=&new templateParser($tags,'cache.txt',2*3600,'template.htm');
// display finished page
echo $tp->display();
?>
Truly, the example is self-explanatory. First, as usual, we include the required class file. Second, we define the values of the $tags array for processing, specifying page title, and the required files for page generation. I’ve chosen to pass file names, but I could have hard-coded HTML instead. Finally, we instantiate a new object from the class, assigning a cache file valid for two hours (2*3600), and the corresponding template file, in this case, "template.htm." The last statement simply displays the page created, either from the parsed template file or directly from the cache file.
Good! We have a template parsing class that offers basic but effective caching capabilities. Let’s congratulate ourselves. If you ever thought that building such a class was an obscure and painful experience, you were mistaken!
Wrapping up
In this article series, I hope I've demonstrated that building a PHP class for parsing template files and caching generated output is not difficult at all. Also, I hope this encourages PHP programmers wishing to taste the power of Object Oriented Programming with real-world applications. Of course, we must keep in mind that PHP4 doesn’t offer the full features for doing so, but with a little bit of will power, the job can be done decently. If you really want to dig deeper in OOP, while keeping your background in PHP, give PHP5 a try. The new and powerful Object Model will amaze you. The challenge is out there. Just try it out.
| | Discuss Building a Template Parser Class with PHP, Part II | | | | | | | In this second part, the class is expanded to add a basic caching mechanism.
Since... | | | | | | Only for aclaration, there is a typo. Where it says witeCache(), should read... | | | | | | We fixed the error, thank you for pointing it out. | | | | | | You're very welcome:-)
Thank you.
| | | | | | Thanks for the great article! As someone pointed out in the comments for Part 1 of... | | | | | | I was hoping that in Part II you might discuss a strategy to parse tags recursively,... | | | | | | This class really rocks. I will use it for sure. Thanks man.
I simply hate... | | | | | | Thank you for the comments.
Well, Reagarding your question about dealing with... | | | | | | Hey, thank you for the kind words about the class.
Regarding your opinion about... | | | | | | Thanks for the comments.
There are several ways to expand the class and add more... | | | | | | I have used Smarty exclusively for the past half dozen projects I have been involved... | | | | | | Thanks a lot for the comments about the class. If this application has been a source... | | | | | | I agree with you and with the author. Smarty has it's place for sure. I also use... | | | | | | Hey, I'm glad you liked the class and I really appreciate your words.
With no doubt... | | | | | | It would be great to see another part to this!
Way to go on I and II. | | | | | | I'll see if I can give a try writing Part III soon.
Thank you. | | | | | | Good article on using a template, but I have a question. I'm doing a similar thing,... | | | | | | Thank you for the kind words about the article. Regarding your question, the answer... | | | | | | I'm a bit confused on how this gets implemented. I see three possible PHP/HTML... | | | | | | There are several ways to generate multiple pages using a template file. With a... | | | | | | I've experienced an issue with this class that I'm not sure how to truly resolve. ... | | | | | | I think that your problem is rather easy to solve. Here's a possible solution:
In... | | | | | | hi,
I'd like to start out by saying what great articles you've made. I've been... | | | | | | Hi friend,
Thank you for the compliments. They're really important.
Regarding... | | | | | | Hmm, I think I see what you're saying. It's a different approach than I was taking... | | | | | | If you want to keep in your template file as much HTML markup as possible, just... | | | | | | Not that I condone script errors, but just curious how you would prevent error... | | | | | | Hello,
About your question, I'll try to give you a general answer, since error... | | | | | | Hey That would be nice part of the class in article 3! | | | | | | Yes, the subject might be covered on a third part. However, I think that all of the... | | | | | | Nice atricles. When I try to use te cache version there is a problem with write... | | | | | | when will be the released of your part III>>> | | | | | | based on
"With this single load.php file you'll generate all of your website pages.... | | | | | | Thank you for commenting on my PHP article. Now, when all the pages are built from... | | | | | | >>> Post your comment now! | | | | | |
|
 |