PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 12 ■ ENTERPRISE PATTERNS

}


function getRequest() {
return $this->request;
}


function setRequest( Request $request ) {
$this->request = $request;
}
}
// empty class for testing
class Request {}


You can then add a Request object in one part of a system:

$reg = Registry::instance();
$reg->setRequest( new Request() );


and access it from another part of the system:


$reg = Registry::instance();
print_r( $reg->getRequest() );


As you can see, the Registry is simply a singleton (see Chapter 9 if you need a reminder about
singleton classes). The code creates and returns a sole instance of the Registry class via the instance()
method. This can then be used to set and retrieve a Request object. Despite the fact that PHP does not
enforce return types, the value returned by getRequest() is guaranteed to be a Request object because of
the type hint in setRequest().
I have been known to throw caution to the winds and use a key-based system, like this:


class Registry {
private static $instance;
private $values = array();


private function __construct() { }


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


function get( $key ) {
if ( isset( $this->values[$key] ) ) {
return $this->values[$key];
}
return null;
}


function set( $key, $value ) {
$this->values[$key] = $value;
}
}

Free download pdf