PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 10 ■ PATTERNS FOR FLEXIBLE OBJECT PROGRAMMING

}


private function compile() {
$lines = getProductFileLines( $this->file );
foreach ( $lines as $line ) {
$id = getIDFromLine( $line );
$name = getNameFromLine( $line );
$this->products[$id] = getProductObjectFromID( $id, $name );
}
}


function getProducts() {
return $this->products;
}


function getProduct( $id ) {
return $this->products[$id];
}
}


From the point of view of client code, now access to Product objects from a log file is much
simplified:


$facade = new ProductFacade( 'test.txt' );
$facade->getProduct( 234 );


Consequences


A Facade is really a very simple concept. It is just a matter of creating a single point of entry for a tier or
subsystem. This has a number of benefits. It helps to decouple distinct areas in a project from one
another. It is useful and convenient for client coders to have access to simple methods that achieve clear
ends. It reduces errors by focusing use of a subsystem in one place, so changes to the subsystem should
cause failure in a predictable location. Errors are also minimized by Facade classes in complex
subsystems where client code might otherwise use internal functions incorrectly.
Despite the simplicity of the Facade pattern, it is all too easy to forget to use it, especially if you are
familiar with the subsystem you are working with. There is a balance to be struck, of course. On the one
hand, the benefit of creating simple interfaces to complex systems should be clear. On the other hand,
one could abstract systems with reckless abandon, and then abstract the abstractions. If you are making
significant simplifications for the clear benefit of client code, and/or shielding it from systems that might
change, then you are probably right to implement the Facade pattern.


Summary


In this chapter, I looked at a few of the ways that classes and objects can be organized in a system. In
particular, I focused on the principle that composition can be used to engender flexibility where
inheritance fails. In both the Composite and Decorator patterns, inheritance is used to promote
composition and to define a common interface that provides guarantees for client code.
You also saw delegation used effectively in these patterns. Finally, I looked at the simple but
powerful Facade pattern. Facade is one of those patterns that many people have been using for years
without having a name to give it. Facade lets you provide a clean point of entry to a tier or subsystem. In
PHP, the Facade pattern is also used to create object wrappers that encapsulate blocks of procedural
code.

Free download pdf