refactored Registry pattern

This commit is contained in:
Dominik Liebler 2019-08-26 06:18:51 +02:00
parent b3f144c4b2
commit 87f8eb1983
No known key found for this signature in database
GPG Key ID: DCE4AADEA26FD47B
4 changed files with 31 additions and 27 deletions

View File

@ -10,9 +10,9 @@ abstract class Registry
* 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
* @var Service[]
*/
private static $storedValues = [];
private static $services = [];
/**
* @var array
@ -21,32 +21,21 @@ abstract class Registry
self::LOGGER,
];
/**
* @param string $key
* @param mixed $value
*
* @return void
*/
public static function set(string $key, $value)
public static function set(string $key, Service $value)
{
if (!in_array($key, self::$allowedKeys)) {
throw new \InvalidArgumentException('Invalid key given');
}
self::$storedValues[$key] = $value;
self::$services[$key] = $value;
}
/**
* @param string $key
*
* @return mixed
*/
public static function get(string $key)
public static function get(string $key): Service
{
if (!in_array($key, self::$allowedKeys) || !isset(self::$storedValues[$key])) {
if (!in_array($key, self::$allowedKeys) || !isset(self::$services[$key])) {
throw new \InvalidArgumentException('Invalid key given');
}
return self::$storedValues[$key];
return self::$services[$key];
}
}

View File

@ -0,0 +1,9 @@
<?php
namespace DesignPatterns\Structural\Registry;
class Service {
}

View File

@ -3,28 +3,34 @@
namespace DesignPatterns\Structural\Registry\Tests;
use DesignPatterns\Structural\Registry\Registry;
use stdClass;
use DesignPatterns\Structural\Registry\Service;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
class RegistryTest extends TestCase
{
/**
* @var Service|MockObject
*/
private $service;
protected function setUp(): void
{
$this->service = $this->getMockBuilder(Service::class)->getMock();
}
public function testSetAndGetLogger()
{
$key = Registry::LOGGER;
$logger = new stdClass();
Registry::set(Registry::LOGGER, $this->service);
Registry::set($key, $logger);
$storedLogger = Registry::get($key);
$this->assertSame($logger, $storedLogger);
$this->assertInstanceOf(stdClass::class, $storedLogger);
$this->assertSame($this->service, Registry::get(Registry::LOGGER));
}
public function testThrowsExceptionWhenTryingToSetInvalidKey()
{
$this->expectException(\InvalidArgumentException::class);
Registry::set('foobar', new stdClass());
Registry::set('foobar', $this->service);
}
/**

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.5 KiB

After

Width:  |  Height:  |  Size: 20 KiB