2019-08-19 18:11:49 +02:00
|
|
|
<?php declare(strict_types=1);
|
2011-09-04 18:33:26 +02:00
|
|
|
|
2014-04-15 23:14:39 -03:00
|
|
|
namespace DesignPatterns\Structural\Registry;
|
2011-09-04 18:33:26 +02:00
|
|
|
|
2019-12-14 12:50:05 +01:00
|
|
|
use InvalidArgumentException;
|
|
|
|
|
2011-09-04 18:33:26 +02:00
|
|
|
abstract class Registry
|
|
|
|
{
|
|
|
|
const LOGGER = 'logger';
|
|
|
|
|
2013-09-13 12:00:39 +02:00
|
|
|
/**
|
2016-09-23 10:47:24 +02:00
|
|
|
* 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!
|
|
|
|
*
|
2019-08-26 06:18:51 +02:00
|
|
|
* @var Service[]
|
2013-09-13 12:00:39 +02:00
|
|
|
*/
|
2019-12-14 12:50:05 +01:00
|
|
|
private static array $services = [];
|
2016-09-23 10:47:24 +02:00
|
|
|
|
2019-12-14 12:50:05 +01:00
|
|
|
private static array $allowedKeys = [
|
2016-09-23 10:47:24 +02:00
|
|
|
self::LOGGER,
|
|
|
|
];
|
2011-09-04 18:33:26 +02:00
|
|
|
|
2019-08-26 06:18:51 +02:00
|
|
|
public static function set(string $key, Service $value)
|
2011-09-04 18:33:26 +02:00
|
|
|
{
|
2016-09-23 10:47:24 +02:00
|
|
|
if (!in_array($key, self::$allowedKeys)) {
|
2019-12-14 12:50:05 +01:00
|
|
|
throw new InvalidArgumentException('Invalid key given');
|
2016-09-23 10:47:24 +02:00
|
|
|
}
|
|
|
|
|
2019-08-26 06:18:51 +02:00
|
|
|
self::$services[$key] = $value;
|
2011-09-04 18:33:26 +02:00
|
|
|
}
|
|
|
|
|
2019-08-26 06:18:51 +02:00
|
|
|
public static function get(string $key): Service
|
2011-09-04 18:33:26 +02:00
|
|
|
{
|
2019-08-26 06:18:51 +02:00
|
|
|
if (!in_array($key, self::$allowedKeys) || !isset(self::$services[$key])) {
|
2019-12-14 12:50:05 +01:00
|
|
|
throw new InvalidArgumentException('Invalid key given');
|
2016-09-23 10:47:24 +02:00
|
|
|
}
|
|
|
|
|
2019-08-26 06:18:51 +02:00
|
|
|
return self::$services[$key];
|
2011-09-04 18:33:26 +02:00
|
|
|
}
|
|
|
|
}
|