Skip to content

Instantly share code, notes, and snippets.

@moaxaca
Last active September 11, 2017 20:34
Show Gist options
  • Save moaxaca/2303bad4db6ce84fd55a5b6b3475f516 to your computer and use it in GitHub Desktop.
Save moaxaca/2303bad4db6ce84fd55a5b6b3475f516 to your computer and use it in GitHub Desktop.
PHP - Dependency Inversion Container
<?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