HomePHP Page 2 - Template-Based Web Development With patTemplate (part 1)
Hard Sell - PHP
Most PHP-based Web sites are a mush of intermingled HTMLmarkupand PHP function calls, making them hard to decipher and maintain. Butthere *is* a simpler way - using templates to separate layout frombusinesslogic. This article shows you how.
patTemplate is a PHP-based template engine designed, in the author's words, to "help you separate program logic or content from layout". Developed by Stephan Schmidt, it is freely available for download and is packaged as a single PHP class which can be easily included in your application.
patTemplate uses templates to simplify maintenance of PHP code, and to separate data from page elements. It assumes that a single Web application is made up of many smaller pieces - it calls these parts "templates" - and it provides an API to link templates together, and to fill them with data.
In patTemplate lingo, a "template" is simply a text file, typically containing both static elements (HTML code, ASCII text et al) and patTemplate variables. When patTemplate parses a template file, it automatically replaces the variables within it with their values (this is referred to as "variable interpolation"). These values may be defined by the developer at run-time, and may be either local to a particular template, or global across all the templates within an application.
As you will see, patTemplate also makes it possible to "nest" one template within another, adding a whole new level of flexibility to this template-based method of doing things. By allowing you to split up a user interface into multiple smaller parts, patTemplate adds reusability to your Web application (a template can be used again and again, even across different projects) and makes it easier to localize the impact of a change.
As if all that wasn't enough, patTemplate also makes it possible to hide or show individual sub-templates, to repeat templates as many times as needed, to iteratively build templates, and to use conditional tests within a template. Since it's not HTML-specific - your template can contain code in any format you like - it can even generate output in ASCII, CSV or XML.
Before proceeding further, you should visit the patTemplate home page at http://www.php-tools.de/ and download a copy of the latest version (2.4 at the time of writing). The package contains the main class file, documentation outlining the exposed methods and variables, and some example scripts.