The Template Class

Since the application needs to produce multiple output formats, you need a way to control the display. For example, the HTML output starts with <html>, but you certainly don’t want that to appear on the command line.

Good programming style says that it’s bad form to mix programming and display logic. This leads to messy code because everything becomes intertwined. Additionally, since you already know you need a minimum of two different types of output, doing everything inline not only makes it harder to add additional output styles, but it’s also more difficult to maintain your existing styles.

Therefore, you should create template objects. Each object should have the same set of display methods, such as getHeader( ) and getFooter( ). However, they’ll return different content—for example, HTML or plain text.

This is the perfect place to use an abstract base class. The abstract class specifies the exact names and prototypes for all your methods. Then, you create one class for each format and make sure that each of those classes extends the base.

The Template class in Example 10-15 has four methods.

Example 10-15. Template abstract class

abstract class Template {
    abstract public function getHeader( );
    abstract public function getBody(DOMDocument $dom);
    abstract public function getFooter( );   

    public function printAll(addressBook $ab) {
        print $this->getHeader( );
        print $this->getBody($ab->toDOM( ));
        print $this->getFooter( );

Two methods—getHeader( ) and getFooter( ...

Get Upgrading to PHP 5 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.