Skip to content

Instantly share code, notes, and snippets.

@sagalbot
Last active April 5, 2017 19:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sagalbot/419194a157c85a2cbb390e7fd8352467 to your computer and use it in GitHub Desktop.
Save sagalbot/419194a157c85a2cbb390e7fd8352467 to your computer and use it in GitHub Desktop.
A bare-bones PHP IoC container.
<?php
interface Container
{
static function bind($name, Callable $resolver);
static function make($name);
}
<?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