Practical PHP Coding Standards – Part 3 / 3

In Part One we looked at PHPDocumentor, and in Part Two we examined the power of template engines. Next, we will look at the third guideline: separate content from layout.

One thing I forgot to mention in Part Two is that another major benefit of a template engine is division of labor. Programmers can program, and designers can design in HTML, then paste in the appropriate tags to display the programmatically generated content. This is also one of the major benefits of separating content from layout and formatting. This is partly achieved through using a template engine. The other half of the equation? Cascading Style Sheets or CSS.

While this may at first seem more like a design issue than a PHP issue, the truth is I have seen way too many lines of code that look like this:


<?PHP
$foo
= '<center><font color="#FF0000">'.$bar.'</font></center>';
?>
...
<?= $foo ?>


Using CSS, you can separate the formatting and layout from the content itself, as follows:

<style type="text/css">
.error {
    color: #FF0000;
    text-align: center;
}
</style>
...
<div class="error"><?= $bar ?></div>


In practice, it is also a good idea to move CSS code as well as JavaScript code off the main page, into separate files and use <link rel=…> to make the contents of these external files available on the main page. It is not only helpful for pushing real content further up the page for purposes of search engine ranking, but it keeps the HTML less cluttered and means less scrolling to get at the body content.

Dynamically generating CSS is typically a bad idea. Unless the application absolutely needs this, generating CSS in PHP puts responsibility for the style elements in the programmer’s court, rather than the designer’s court. Calling up different stylesheets that can be manipulated statically by a designer is a different matter — this is an excellent way to provide a different look-and-feel to your web application based on, for example, the company of the person that is using the application. Such ‘rebranding’ can often be rolled together with custom content on a per-company basis to create a unique portal environment.

The power of CSS as a means to replacing tables for layout is strikingly displayed in the CSS Zen Garden. In practical usage, I find a combination of tables and CSS still makes for the fastest and most efficient way to create layout. As browsers (and designers) mature, it appears that <div> will be fast replacing <table> not only for formatting and style but layout as well.

Keeping content separate from layout keeps the both the division of work and the division of elements (PHP, HTML, CSS) very clear. This increases maintainability as well as accountability for each aspect of the site — designers design, coders code.

I hope you have enjoyed this three-part series and that your team development projects get a quick and painless boost in productivity by following these simple guidelines.