PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 12 ■ ENTERPRISE PATTERNS


Acquiring the information is easy enough, but how would I get it to the data layer where it is later
used? And what about all the other configuration information I must disseminate throughout my
system?
One answer would be to pass this information around the system from object to object: from a
controller object responsible for handling requests, through to objects in the business logic layer, and on
to an object responsible for talking to the database.
This is entirely feasible. In fact, you could pass the ApplicationHelper object itself around, or
alternatively, a more specialized Context object. Either way, contextual information is transmitted
through the layers of your system to the object or objects that need it.
The trade-off is that in order to do this, you must alter the interface of all the objects that relay the
context object whether they need to use it or not. Clearly, this undermines loose coupling to some
extent.
The Registry pattern provides an alternative that is not without its own consequences.
A registry is simply a class that provides access to data (usually, but not exclusively, objects) via static
methods (or via instance methods on a singleton). Every object in a system, therefore, has access to
these objects.
The term “Registry” is drawn from Fowler’s Patterns of Enterprise Application Architecture, but like
all patterns, implementations pop up everywhere. David Hunt and David Thomas (The Pragmatic
Programmer) liken a registry class to a police incident notice board. Detectives on one shift leave
evidence and sketches on the board, which are then picked up by new detectives on another shift. I have
also seen the Registry pattern called Whiteboard and Blackboard.


Implementation


Figure 12–2 shows a Registry object whose job it is to store and serve Request objects.


Figure 12–2. A simple registry


Here is this class in code form:

class Registry {
private static $instance;
private $request;


private function __construct() { }


static function instance() {
if (! isset( self::$instance ) ) { self::$instance = new self(); }
return self::$instance;

Free download pdf