O'Reilly logo

Upgrading to PHP 5 by Adam Trachtenberg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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( ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required