The Registry design pattern gives us a way to overcome scoping complexities in your object-oriented programs. In this post I want to talk about how we use a Registry class in the MojoMVC.
In the MojoMVC, every request requires a Request object. There are times when other objects need that information. PHP has global variables by default, with local variables inside regular functions, and public, protected, and private methods inside classes. Since we don’t speak Kludge here, we need a another strategy for passing information around. The Registry pattern fills the bill.
We use the Registry class to take advantge the fact that classes have super global visibility—they can walk through walls like the super global variables ($_GET, $_POST, etc), functions, and constants. In other words, our Registry class can function as a super global delivery messenger as long as we give it some static setters and getters.
The Registry Class
1 class Registry extends Base {
2 static private $data = array();
3
4 private function __construct() {}
5
6 static public function get($key)
7 {
8 return self::$data[$key];
9 }
10
11 static public function set($key,$value)
12 {
13 self::$data[$key] = $value;
14 }
15 }
We can use it like this:
Registry::set(‘string’, ‘this is the name’);
print Registry::get(‘string’); // output: this is the name
class NextClass {
function __construct() {
print Registry::get(‘string’);
}
}
$n = new NextClass; // output: this is the name
Now we have a class that walks through walls to deliver the values stored inside it. All we have to do is store the Request object in the Registry, like this:
You’re probably wondering where $this->r came from. That’s an interesting story, but it will have to wait until next time.
For more information on the Registry pattern, check out your friendly Google.
