PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 12 ■ ENTERPRISE PATTERNS

Remember that the aim of this chapter is to illustrate key enterprise design patterns and not to build
a working system. Reflecting the interdependent nature of design patterns, most of these examples
overlap to a large extent with code examples, making good use of ground covered elsewhere in the
chapter. As this code is mainly designed to demonstrate enterprise patterns, much of it does not fulfill all
the criteria demanded by a production system. In particular, I omit error checking where it might stand
in the way of clarity. You should approach the examples as a means of illustrating the patterns they
implement, rather than as building blocks in a framework or application.


Cheating Before We Start


Most of the patterns in this book find a natural place in the layers of an enterprise architecture. But some
patterns are so basic that they stand outside of this structure. The Registry pattern is a good example of
this. In fact, Registry is a powerful way of breaking out of the constraints laid down by layering. It is the
exception that allows for the smooth running of the rule.


Registry


The Registry pattern is all about providing systemwide access to objects. It is an article of faith that
globals are bad. Like other sins, though, global data is fatally attractive. This is so much the case that
object-oriented architects have felt it necessary to reinvent globals under a new name. You encountered
the Singleton pattern in Chapter 9. It is true that singleton objects do not suffer from all the ills that beset
global variables. In particular, you cannot overwrite a singleton by accident. Singletons, then, are low-fat
globals. You should remain suspicious of singleton objects, though, because they invite you to anchor
your classes into a system, thereby introducing coupling.
Even so, singletons are so useful at times that many programmers (including me) can’t bring
themselves to give them up.


The Problem


As you have seen, many enterprise systems are divided into layers, with each layer communicating with
its neighbors only through tightly defined conduits. This separation of tiers makes an application
flexible. You can replace or otherwise develop each tier with the minimum impact on the rest of the
system. What happens, though, when you acquire information in a tier that you later need in another
noncontiguous layer?
Let’s say that I acquire configuration data in an ApplicationHelper class:


// woo\controller\ApplicationHelper
function getOptions() {
if (! file_exists( "data/woo_options.xml" ) ) {
throw new woo_base_AppException(
"Could not find options file" );
}
$options = simplexml_load_file( "data/woo_options.xml" );
$dsn = (string)$options->dsn;
// what do we do with this now?
// ...
}

Free download pdf