Last active
April 5, 2017 19:35
-
-
Save sagalbot/419194a157c85a2cbb390e7fd8352467 to your computer and use it in GitHub Desktop.
A bare-bones PHP IoC container.
This file contains hidden or 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 | |
interface Container | |
{ | |
static function bind($name, Callable $resolver); | |
static function make($name); | |
} |
This file contains hidden or 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 IoC | |
*/ | |
class IoC implements Container | |
{ | |
/** | |
* @var array | |
*/ | |
protected static $registry = []; | |
/** | |
* Bind into the container. | |
* @param $name | |
* @param callable $resolver | |
*/ | |
public static function bind($name, Callable $resolver) | |
{ | |
static::$registry[$name] = $resolver; | |
} | |
/** | |
* Resolve out of the container. | |
* @param $name | |
* | |
* @return mixed | |
* @throws Exception | |
*/ | |
public static function make($name) | |
{ | |
if( ! array_key_exists($name, static::$registry) ) | |
{ | |
throw new Exception('Alias does not exist in the IoC registry.'); | |
} | |
return static::$registry[$name](); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment