123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- <?php
-
- namespace SCF\Core;
-
- class DI {
- /**
- * @var $instance
- */
- private static $instance;
-
- /**
- * @var array $container
- */
- private $container = [];
-
- /**
- * DI constructor.
- */
- private function __construct()
- {
-
- }
-
- /**
- *
- */
- private function __clone()
- {
-
- }
-
- /**
- * @return DI
- */
- public static function getInstance()
- {
- if(self::$instance === null) {
- self::$instance = new self();
- }
-
- return self::$instance;
- }
-
- /**
- * @param $name
- * @param $classDefinition
- * @param bool $shared
- */
- public function set($name, $classDefinition, $shared = false)
- {
- $this->container[$name] = (object)['def' => $classDefinition, 'shared' => $shared, 'instance' => null];
- }
-
- /**
- * @param $name
- * @return mixed
- */
- public function get($name)
- {
- if(!isset($this->container[$name])) {
- throw new \RuntimeException('Angeforderter Service '. $name .' nicht definiert');
- }
-
- $service = $this->container[$name];
-
- if(!$service->shared) {
- return $this->createInstance($service->def, false);
- }
-
- if($service->instance === null) {
- $service->instance = $this->createInstance($service->def, true);
- }
-
- return $service->instance;
- }
-
- /**
- * @param $definition
- * @param $shared
- * @return mixed
- */
- private function createInstance($definition, $shared)
- {
- if(is_callable($definition)) {
- return $definition();
- }
-
- if(is_string($definition)) {
- return new $definition;
- }
-
- if(is_object($definition)) {
- if($shared) {
- return $definition;
- } else {
- return new $definition;
- }
- }
-
- throw new \RuntimeException('Malformed service definition!');
- }
-
- }
|