2.11. Registry
2.11.1. Purpose
To implement a central storage for objects often used throughout theapplication, is typically implemented using an abstract class with onlystatic methods (or using the Singleton pattern). Remember that this introducesglobal state, which should be avoided at all times! Instead implement it using Dependency Injection!
2.11.2. Examples
- Zend Framework 1:
Zend_Registry
holds the application’s loggerobject, front controller etc. - Yii Framework:
CWebApplication
holds all the applicationcomponents, such asCWebUser
,CUrlManager
, etc.
2.11.3. UML Diagram
2.11.4. Code
You can also find this code on GitHub
Registry.php
- <?php
- namespace DesignPatterns\Structural\Registry;
- abstract class Registry
- {
- const LOGGER = 'logger';
- /**
- * this introduces global state in your application which can not be mocked up for testing
- * and is therefor considered an anti-pattern! Use dependency injection instead!
- *
- * @var array
- */
- private static $storedValues = [];
- /**
- * @var array
- */
- private static $allowedKeys = [
- self::LOGGER,
- ];
- /**
- * @param string $key
- * @param mixed $value
- *
- * @return void
- */
- public static function set(string $key, $value)
- {
- if (!in_array($key, self::$allowedKeys)) {
- throw new \InvalidArgumentException('Invalid key given');
- }
- self::$storedValues[$key] = $value;
- }
- /**
- * @param string $key
- *
- * @return mixed
- */
- public static function get(string $key)
- {
- if (!in_array($key, self::$allowedKeys) || !isset(self::$storedValues[$key])) {
- throw new \InvalidArgumentException('Invalid key given');
- }
- return self::$storedValues[$key];
- }
- }
2.11.5. Test
Tests/RegistryTest.php
- <?php
- namespace DesignPatterns\Structural\Registry\Tests;
- use DesignPatterns\Structural\Registry\Registry;
- use stdClass;
- use PHPUnit\Framework\TestCase;
- class RegistryTest extends TestCase
- {
- public function testSetAndGetLogger()
- {
- $key = Registry::LOGGER;
- $logger = new stdClass();
- Registry::set($key, $logger);
- $storedLogger = Registry::get($key);
- $this->assertSame($logger, $storedLogger);
- $this->assertInstanceOf(stdClass::class, $storedLogger);
- }
- /**
- * @expectedException \InvalidArgumentException
- */
- public function testThrowsExceptionWhenTryingToSetInvalidKey()
- {
- Registry::set('foobar', new stdClass());
- }
- /**
- * notice @runInSeparateProcess here: without it, a previous test might have set it already and
- * testing would not be possible. That's why you should implement Dependency Injection where an
- * injected class may easily be replaced by a mockup
- *
- * @runInSeparateProcess
- * @expectedException \InvalidArgumentException
- */
- public function testThrowsExceptionWhenTryingToGetNotSetKey()
- {
- Registry::get(Registry::LOGGER);
- }
- }