Undoubtedly, the best way to see the real capabilities of the “TemplateProcessor” class is simply by setting up an example that shows how all the template files I showed you previously are used together. In this example, I’ll specify different expiration times for each template file, where the “header_template.htm” file will have an expiry of 3600 seconds, then the “body_template.htm” file will be updated each 60 seconds, and finally the “footer_template.htm” file will be parsed at intervals of 3600 seconds too. Additionally, I’ll include a MySQL dataset within the main section of the web page, which will be fetched by the MySQL wrapping classes that I showed in the previous article (they won’t be listed here). Having specified the set of parameters for this example, here’s the code sample that uses the “TemplateProcessor” class: try{ As you can see, the above script first connects to MySQL and fetches a trivial result set from a “users” database table. Next, the corresponding “$pageSections” input array is defined, which contains the shortened names of each web page section along with their cache expiration times. At this stage, do you see how this set of parameters is used internally by the “TemplateProcessor” class? I hope you do. Now, turn your attention to the second $tags array; notice that this is a recursive array, where all the tags of a specific page section are the elements of another array too. Of course, you can go as deep as you want in defining recursive arrays, as long as the template files contain the appropriate structure of nested placeholders. Right, that was the hard part. Once the proper input arrays have been defined, they’re passed as parameters to an instance of the template processor class, and finally the whole web page is displayed by using the “getHTML()” method. Of course, you’ll have a much better idea of the functionality of the “TemplateProcessor” class if you test it for yourself, thus I included a ZIP file here (which is also linked to at the beginning of this article), containing the class and additional sample files. I hope you enjoy playing with the source code I provided you, and as usual, feel free to introduce your own modifications. Final thoughts In this last tutorial of the series I went through the making of a PHP 5 extensible template processor class, which not only has most of the features that you saw in my previous article, but also is capable of working with multiple template files, in this way implementing the so-called chunked caching. As you’ve seen here, the source code of the class is pretty easy to follow, which means that you shouldn’t have trouble tweaking it, in order to meet your personal requirements. See you in the next PHP tutorial!
blog comments powered by Disqus |