Here’s another super-simple design pattern, implemented in PHP.
class Registry { private $values = array(); public function get($key) { if (!isset($this->values->$key)) { throw new OutOfBoundsException("$key not in registry"); } return $this->values->$key; } public function set($key, $val) { if (!isset($this->values->$key)) { throw new OverflowException("$key already in registry"); } $this->values->$key = $val; } }
The registry pattern is used to store information that can be used throughout your application. You could use a registry to store a bunch of application settings, for example.
I’ve seen this implemented with the magic getters and setters in php, but then you end up with an object that appears to just be setting public properties. It’s not the most readable solution and it is unintuitive to expect an exception when setting a public property.
It is often implemented as a singleton, but it doesn’t have to be. In general singletons are bad because they introduce global state into your code and are hard to write test cases for. If you don’t want to use your registry as a singleton, just do an inversion of control. The downside is having to pass around the registry as a parameter, but trust me: it’s worth the effort.