Registry.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. /**
  3. * Pimf
  4. *
  5. * @copyright Copyright (c) Gjero Krsteski (http://krsteski.de)
  6. * @license http://krsteski.de/new-bsd-license New BSD License
  7. */
  8. namespace Pimf;
  9. /**
  10. * A well-known object that other objects can use to find common objects and services.
  11. * Acts also as a dependency injection container.
  12. *
  13. * <code>
  14. * $registry = new Registry();
  15. * $registry->your_key = "123";
  16. *
  17. * // or ..
  18. *
  19. * Registry::set('your_key', "123")
  20. * Registry::get('your_key')
  21. * </code>
  22. *
  23. * @package Pimf
  24. * @author Gjero Krsteski <[email protected]>
  25. *
  26. * @property EntityManager $em
  27. * @property Logger $logger
  28. * @property Environment $env
  29. * @property array $conf
  30. * @property router $router
  31. */
  32. class Registry
  33. {
  34. /**
  35. * The temporary storage for the accumulator.
  36. *
  37. * @var \ArrayObject
  38. */
  39. protected static $battery;
  40. /**
  41. * Re-initialises the data.
  42. *
  43. * @return void
  44. */
  45. protected static function init()
  46. {
  47. if (!self::$battery) {
  48. self::$battery = new \ArrayObject(array(), \ArrayObject::STD_PROP_LIST);
  49. }
  50. }
  51. /**
  52. * @param mixed $namespace The namespace or identifier.
  53. * @param mixed $value The value.
  54. */
  55. public function __set($namespace, $value)
  56. {
  57. self::set($namespace, $value);
  58. }
  59. /**
  60. * @param mixed $namespace The namespace or identifier.
  61. * @param mixed $value The value.
  62. *
  63. * @throws \LogicException If key should be overwritten.
  64. */
  65. public static function set($namespace, $value)
  66. {
  67. self::init();
  68. if (is_resource($value)) {
  69. throw new \LogicException('storing resources in a registry is not permitted!');
  70. }
  71. self::$battery->offsetSet($namespace, $value);
  72. }
  73. /**
  74. * @param mixed $namespace The namespace or identifier.
  75. *
  76. * @return mixed
  77. */
  78. public function __get($namespace)
  79. {
  80. return self::get($namespace);
  81. }
  82. /**
  83. * @param string|integer $namespace The namespace or identifier.
  84. * @param mixed $defaultValue
  85. *
  86. * @return mixed|null
  87. */
  88. public static function get($namespace, $defaultValue = null)
  89. {
  90. self::init();
  91. if (self::$battery->offsetExists($namespace)) {
  92. return self::$battery->offsetGet($namespace);
  93. }
  94. return $defaultValue;
  95. }
  96. }