Last active
September 11, 2017 20:34
-
-
Save moaxaca/2303bad4db6ce84fd55a5b6b3475f516 to your computer and use it in GitHub Desktop.
PHP - Dependency Inversion Container
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Class DIC - Dependency Inversion Container | |
* - Lazy Loads all objects into existence | |
*/ | |
class DIC | |
{ | |
/** | |
* Holds all callable methods to create our objects | |
* @var array | |
*/ | |
private $dependencies = array(); | |
/** | |
* Holds all instantiated objects | |
* @var array | |
*/ | |
private $loadedDependencies = array(); | |
/** | |
* Attempts to pull dependency from the container | |
* @param $name | |
* @return object | |
* @throws \Exception | |
*/ | |
public function __get($name) : object | |
{ | |
if (isset($this->loadedDependencies[$name])) { | |
return $this->loadedDependencies[$name]; | |
} else if (isset($this->dependencies)) { | |
$dependency = $this->dependencies[$name](); | |
$this->loadedDependencies[$name] = $dependency; | |
return $dependency; | |
} else { | |
throw new \Exception('Dependency is\'nt register'); | |
} | |
} | |
/** | |
* Register dependency and construction method | |
* @param string $name | |
* @param callable $method | |
* @throws \Exception | |
*/ | |
public function registerDependency(string $name, callable $method) : void | |
{ | |
if (!isset($this->dependencies[$name])) { | |
$this->dependencies[$name] = $method; | |
} else { | |
throw new \Exception('Dependency with that name is already registered'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment