Posted 18 February 2005 by Robert Peake.

In Part One we examined PHPDocumentor–a powerful tool to document your code, and some pointers on how to use DocBlocks. Now, the second directive is: Separate Code From Content.

This means use a templating system. The most basic form of templating system is to simply use PHP itself to only output variables and maybe perform some minimal formatting on the variable output. For example:

        <?= $foo; ?>
        <?= date("l dS of F Y h:i:s A", $bar); ?>

Other examples of templating systems include Smarty and Flexy.

Using a templating system means making a conscious decision to divide programmatically generated content up into variables. The criteria are:

  • Where the string will live on the page (layout)
  • How the string will look in terms of style (formatting)

The end result is that HTML tags and content should not be output from the main program using print or echo wherever possible. Instead, variables should be passed into the template, and the template should handle outputting the contents of the variable as well as minor formatting (for example, transforming an ISO date into a more human-readable date).

Separating code from content has many benefits. Probably the single greatest impact is maintainability. Not having to think in both PHP and HTML makes a developer’s life easier. Much easier. Furthermore, multi-language sites benefit tremendously from using templates. Finally, a template system can be used to change the “skin” or overall look-and-feel of an application without changing the underlying functionality. The Serendipity blog system I am using now is skinnable, and the look-and-feel of my site was rendered entirely through use of the web-based admin tool to choose sidebar content and CSS for look-and-feel. More on the power of layout-independent content in Part Three.

There are, of course, some exceptions to the use of templates. For example, when returning large sets of MySQL data into a table, it is often much faster to display the results of mysql_fetch_array() or mysql_fetch_assoc directly using echo. This kind of tradeoff can be easily achieved by using PHP as your template system. Exceptions made for sake of performance are important to note in your documentation, so that developers understand you were being deliberate, not lazy, in your choices.

Next up: separating content from layout.