Web Development with PHP 4.0 and FastTemplate 1.1.0

by Bill Cunningham

One thing about the web development business: the software tools we use evolve so rapidly that it's hard to keep up with them. A year ago, I hadn't even heard of the web-scripting language, PHP. Today I write PHP full-time at my job.

There we have two teams: one team writes strictly PHP code using Red Hat Linux-based PCs, and the other does strictly graphics design using DreamWeaver on NT-based PCs. The marketing department sketches out the pages; the graphics team builds the pages with the data sections of the pages stubbed out. The code team takes over and, using PHP's ability to integrate with HTML seamlessly, brings active data into the page stubs.

And that's all fine—until someone wants to change, say, the text on a certain submit button that appears on 46 pages throughout the site. This means 46 changes to 46 files now have to be made just to alter the appearance of one little button! Thank goodness for grep.

But there's a way to avoid all this, and that's the subject of this article. By using HTML templates, the button mentioned above can be fixed by making a simple change to one file. Templates enable the physical separation of PHP code and HTML. Changes to the PHP code in no way affect the HTML, and vice versa.

Templates operate like this: a PHP program opens and parses external files that contain the HTML for a page. The HTML files contain placeholders for data that will be substituted in at runtime. The tags usually look something like: {ITEM}. When a tag is encountered, the PHP program substitutes the right data for the tag. This way, the PHP code files can be kept completely separate from the HTML files, and the coders and designers don't accidently mess up each other's work.

There are several open-source template packages available. Some are more powerful and complicated than others. One package that I believe strikes a good balance between speed of execution and ease of use is FastTemplate 1.1.0 from CDI. Joe Harris, the author, has released FastTemplate under the General Artistic License. Joe writes in the documentation that FastTemplate 1.1.0 is actually a PHP port of a Perl module of the same name. The Perl module was written by Jason Moore.

The idea in using FastTemplate is to break down a web page into its most basic components: individual buttons, checkboxes, even lines of text. Tables must be broken down into headers and rows, and rows must be broken into cells. Each component is given its own file with the static HTML and a special tag for the variable data. Then, the page is built up from these simple components. Finally, you end up with a file like our main.tpl that simply contains the tag, {BODY}. Some prefer to call it {CONTENT}; the exact name is immaterial. This top-level tag is replaced with the data for the total page. If desired, it can even be the top-level file for every page in your site. Therefore, a change to this file will change the look of your whole site. We will do exactly that in the example program.

There are several positive implications here. To use templates, you need to have the exact content of all your pages absolutely nailed down to the last detail because you are going to be making template files for each widget on the page. This is good because it forces you to be an engineer and makes it very difficult to be a hacker. To add a feature after the fact will require changes to at least three files, not just one. Your site will be better for this because your design will be more thorough, detailed and more carefully planned.

Early on, it seems like you are accumulating a lot of very small template files, and while this is true, the templates are reusable to a large extent. As the size of your application grows, the proportion of template files shrinks. You can also put more than one data tag in a template file. This reduces the number of template files but also makes the template less reusable.

To appreciate what FastTemplate can do for web site maintainability, let's see it in action. I'm assuming that you have access to a Linux server already running Apache, PHP and a relational database (I used MySQL), and that you can make changes to a few files and directories normally owned by root.

Installing FastTemplate is about as easy as it gets. The home page is www.thewebmasters.net/php/FastTemplate.phtml. Download the file FastTemplate-1_1_0.tar.gz and, if you're running PHP 4.0, the diff file (php4.diff) as well. Move the download to your document root and untar it. The directory, FastTemplate/, will be created. If you're running PHP 4.0, place php4.diff in FastTemplate/ and run these commands:

patch class.FastTemplate.php3 php4.diff
mv class.FastTemplate.php3 class.FastTemplate.php

Then, move class.FastTemplate.php into your PHP include directory. If you're not sure where this directory is, check the file, php.ini. It's found in /usr/local/lib/ by default. Look for the “include path” setting. It is also possible to include class.FastTemplate.php explicitly into PHP programs with an include( ) statement, but this takes extra work and I tend to forget to do it. That's it for installing FastTemplate.

Next, make another directory somewhere under your document root for this example's files. You will need the files in Listing 1, Listing 2 and Listing 3. Listing 4 will need to be broken down into the individual template files [see ftp://ssc.com/pub/lj/listings/issue86/].

Listing 1. index.php

Listing 2. mysql.php

Listing 3. goodbye.php

This example, though short and simple, illustrates that FastTemplate can easily handle a table that is dynamic in both rows and columns. As far as individual elements of a page go, that's about as complicated as it gets.

Look at Listing 1. To use FastTemplate, we simply include class.FastTemplate.php and declare an instance. The (“.”) in our declaration indicates that our supporting templates are found in the current directory. They could just as easily be in another. The FastTemplate class has four main methods: define( ), assign( ), parse( ) and print( ).

The define( ) method maps external filenames to handles that our program will use. Note that the templates need not end in .tpl. You will probably need only one call to define( ) in any program.

The assign( ) method maps the data tags (minus the {}s) to the data we want to replace them with. There can be many assign( ) calls throughout your program. Begin by dealing with the smallest, most basic components first and build more complex components with them.

For me, parse( ) was the hardest method to understand. This method parses a template, makes the data-for-tag substitution and stores the result in a local variable. The local variable is the first parameter to parse( ). The second parameter is the file handle we defined in define( ). If the second parameter to parse( ) begins with a “.” we append the new value to the previous, if any. We use this technique to populate the database selector in the example. The PHP program's main muscle will be used to retrieve or calculate data for assigning and parsing.

Finally, print( ) outputs the contents of the most recent parse by default. We can also pass parsed results to it as a parameter. There can be more than one print( ) on a page, and sometimes this is the easiest way to get a page on the screen. And, there is usually more than one way to generate a page. If it works and it's efficient, it's good.

So let's see the example. With a browser, load the examples in Listing 1, and you should see something like Figure 1. Select a database with the selector, enter a query, press the EXECUTE button and the results of your query are displayed (see Figure 2).

Figure 1. PHP SQL Query Test Page

Figure 2. Output from the Test Query

Now, assume the role of graphics designer. Your job is to totally change the look of the entire application. Your imaginary boss has just said that the grey background has to go—he wants it to be yellow. And he wants everything centered on the page, not left justified. And by the way, he wants all the text in green. With a FastTemplate-based site, you can make all this happen in less than a minute by editing the top-level template file, main.tpl.

Better web editors exist, but Netscape Composer can do the job. Here's how to do it: in Netscape Navigator, select File --> Open Page. In the dialog that appears, enter or browse the full path to main.tpl in your example directory, and click “Open in Composer”. Netscape Composer will open a large window with a single word, {BODY}, displayed in the composer edit area (see Figure 3). That's the HTML-rendered version of main.tpl. To make the boss' changes, first select Edit --> Select All. {BODY}, including parentheses, should be highlighted in yellow. Now select Format --> Align --> Center. That takes care of centering. Edit --> Select All again. Now select Format --> Text Color, and pick a nice dark green from the swatches selector. Click OK. You should now see {BODY} in dark green. That's two down, one to go. Select Format --> Page Colors and Properties. Select the Use Custom Colors button in the radiogroup at the top of the Colors and Background Tab. Then select Background. Pick yellow from the Swatches Tab in the dialog that appears. Click OK, Apply and OK again. Your background in Composer should already be yellow. Now select File --> Save, then File --> Close.

Figure 3. The Main FastTemplate File Open for Editing

Now reload the query page from the example. All three changes should now be in effect: yellow background, green text and everything centered, yet the application should still work programmatically as it always did (see Figure 4 and Figure 5). Although this example is very simple, I think the potential here is obvious.

Figure 4. The New Template Is Automatically Applied to the Query Test Page

Figure 5. Template Applied to the Output from the Query

There are some issues that you have to consider with FastTemplate. For one, there are a lot of small files that must be managed and also read from disk every time the page is accessed. This can cause significant performance degradation on a busy site. On sites with infrequent access, this may not be a matter for concern. In some cases, you may wish to have a single template for each page in your site to cut down on the number of template files.

Benjamin Kahn is hosting a web page for an extension of FastTemplate called Cached FastTemplate (http://zoned.net:81/~xkahn/php/fasttemplate/). Cached FastTemplate adds several performance enhancing features to FastTemplate. With this package, pages or parts of a page can be cached in memory, and the caching rules are configurable. This is worth checking out once you get comfortable with FastTemplate.

As I quickly learned at my new job, it's not enough to develop a web site that's good today. It must be scalable and maintainable, too. HTML generators like DreamWeaver, while easy to use, produce HTML that is downright ugly. You don't want to be ferreting through those files looking for your PHP code. HTML templates like FastTemplate can do a lot to enhance the quality of life for web developers.

Bill Cunningham recently retired from the US Marine Corps where he worked as a Solaris systems administrator. He is now employed by Heafner Tire Group of Charlotte, North Carolina as a web developer at a Linux/MySQL-based site.
Load Disqus comments