PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 10 ■ PATTERNS FOR FLEXIBLE OBJECT PROGRAMMING


I can now acquire a polluted tile very easily:

$tile = new PollutedPlains();
print $tile->getWealthFactor();


You can see the class diagram for this example in Figure 10–3.

Figure 10–3. Building variation into an inheritance tree


This structure is obviously inflexible. I can get plains with diamonds. I can get polluted plains. But
can I get them both? Clearly not, unless I am willing to perpetrate the horror that is
PollutedDiamondPlains. This situation can only get worse when I introduce the Forest class, which can
also have diamonds and pollution.
This is an extreme example, of course, but the point is made. Relying entirely on inheritance to
define your functionality can lead to a multiplicity of classes and a tendency toward duplication.
Let’s take a more commonplace example at this point. Serious web applications often have to
perform a range of actions on a request before a task is initiated to form a response. You might need to
authenticate the user, for example, and to log the request. Perhaps you should process the request to
build a data structure from raw input. Finally, you must perform your core processing. You are
presented with the same problem.
You can extend the functionality of a base ProcessRequest class with additional processing in a
derived LogRequest class, in a StructureRequest class, and in an AuthenticateRequest class. You can see
this class hierarchy in Figure 10–4.

Free download pdf