You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DI.php 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. namespace SCF\Core;
  3. class DI {
  4. /**
  5. * @var $instance
  6. */
  7. private static $instance;
  8. /**
  9. * @var array $container
  10. */
  11. private $container = [];
  12. /**
  13. * DI constructor.
  14. */
  15. private function __construct()
  16. {
  17. }
  18. /**
  19. *
  20. */
  21. private function __clone()
  22. {
  23. }
  24. /**
  25. * @return DI
  26. */
  27. public static function getInstance()
  28. {
  29. if(self::$instance === null) {
  30. self::$instance = new self();
  31. }
  32. return self::$instance;
  33. }
  34. /**
  35. * @param $name
  36. * @param $classDefinition
  37. * @param bool $shared
  38. */
  39. public function set($name, $classDefinition, $shared = false)
  40. {
  41. $this->container[$name] = (object)['def' => $classDefinition, 'shared' => $shared, 'instance' => null];
  42. }
  43. /**
  44. * @param $name
  45. * @return mixed
  46. */
  47. public function get($name)
  48. {
  49. if(!isset($this->container[$name])) {
  50. throw new \RuntimeException('Angeforderter Service '. $name .' nicht definiert');
  51. }
  52. $service = $this->container[$name];
  53. if(!$service->shared) {
  54. return $this->createInstance($service->def, false);
  55. }
  56. if($service->instance === null) {
  57. $service->instance = $this->createInstance($service->def, true);
  58. }
  59. return $service->instance;
  60. }
  61. /**
  62. * @param $definition
  63. * @param $shared
  64. * @return mixed
  65. */
  66. private function createInstance($definition, $shared)
  67. {
  68. if(is_callable($definition)) {
  69. return $definition();
  70. }
  71. if(is_string($definition)) {
  72. return new $definition;
  73. }
  74. if(is_object($definition)) {
  75. if($shared) {
  76. return $definition;
  77. } else {
  78. return new $definition;
  79. }
  80. }
  81. throw new \RuntimeException('Malformed service definition!');
  82. }
  83. }