Registry.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace AlexLcDee\RegistryContainer;
  3. class Registry implements RegistryInterface
  4. {
  5. /**
  6. * @var Registry
  7. */
  8. private static $instance;
  9. /**
  10. * @var CategoriesContainer
  11. */
  12. private $container;
  13. private function __construct($typesMap)
  14. {
  15. $this->container = new CategoriesContainer();
  16. foreach ($typesMap as $category => $type) {
  17. $this->container->set($category, new ItemsContainer($type));
  18. }
  19. }
  20. public static function init($typesMap)
  21. {
  22. if(static::$instance !== null) {
  23. throw new RegistryException('Registry can be initialized only once.');
  24. }
  25. static::$instance = new static($typesMap);
  26. return static::$instance;
  27. }
  28. /**
  29. * @param string $category
  30. * @param RegistrableItem $item
  31. * @throws RegistryException
  32. */
  33. public static function add($category, RegistrableItem $item)
  34. {
  35. if (!static::$instance->container->contains($category)) {
  36. throw new RegistryException(strtr('Registry does not contain category "{category}"', [
  37. '{category}' => $category
  38. ]));
  39. }
  40. static::$instance->container->get($category)->add($item);
  41. }
  42. /**
  43. * @param string $category
  44. * @return ItemsContainer
  45. * @throws RegistryException
  46. */
  47. public static function get($category)
  48. {
  49. if (!static::$instance->container->contains($category)) {
  50. throw new RegistryException(strtr('Registry does not contain category "{category}"', [
  51. '{category}' => $category
  52. ]));
  53. }
  54. return static::$instance->container->get($category);
  55. }
  56. }