O'Reilly logo

PHP Hacks by Jack D. Herrington

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

Hack #70. Abstract Construction Code with a Builder

Use the Builder pattern to abstract code that performs a routine construction task, such as composing HTML or text for an email.

I've always found that code that constructs something is some of the most elegant code in a system. I suppose that's just because I spent a year writing a book on code generation, which is all about constructing code.

Tip

By the way, the book is Code Generation in Action (Manning). It_s still available and makes an excellent holiday gift for friends and family.

An example of construction code is the code that reads an XML document off the disk and constructs an in-memory representation of that structure. Another is a module of code that constructs an email message to tell a customer she is behind on her payments.

It's the late-payment mail that I want to focus on in this hack; but I'm going to do it with a twist. I'm going to use the Builder pattern so that the same code that creates a message in HTML can also create a message in XHTML or text format.

I'm going to have the code that writes the past-due notice use a builder instead of just creating the string directly. This builder object will have a set of methods, as shown in Figure 7-4. The startBody() and endBody() methods wrap the creation of the message. The addText() method adds some text, and the addBreak() method adds a line break.

The output builder hierarchy

Figure 7-4. The ...

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