Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@igorw
Last active December 23, 2015 00:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save igorw/6557390 to your computer and use it in GitHub Desktop.
Save igorw/6557390 to your computer and use it in GitHub Desktop.
<?php
namespace Yolo;
class ServiceNotFoundException extends \RuntimeException {}
class RecursiveServiceDefinitionException extends \RuntimeException {}
class InvalidArgumentException extends \RuntimeException {}
class Container
{
private $definitions = [];
private $instances = [];
function __construct(array $definitions)
{
$this->definitions = $definitions;
}
function get($name)
{
if (isset($this->instances[$name])) {
return $this->instances[$name];
}
if (!isset($this->definitions[$name])) {
throw new ServiceNotFoundException($name);
}
$definition = $this->definitions[$name];
$instance = $this->createInstance($name, $definition);
$this->instances[$name] = $instance;
return $instance;
}
private function createInstance($name, $definition)
{
$class = $definition['class'];
$arguments = isset($definition['arguments']) ? $definition['arguments'] : [];
$resolvedArgs = array_map([$this, 'resolveArgument'], $arguments);
$reflection = new \ReflectionClass($class);
return $reflection->newInstanceArgs($resolvedArgs);
}
private function resolveArgument(array $arg)
{
if (isset($arg['ref'])) {
return $this->get($arg['ref']);
}
if (isset($arg['value'])) {
return $arg['value'];
}
throw new InvalidArgumentException(sprintf('Got invalid service argument %s', json_encode($arg)));
}
}
namespace _;
use Yolo\Container;
use Yolo\RecursiveServiceDefinitionException;
class Foo
{
public $bar;
function __construct(Bar $bar)
{
$this->bar = $bar;
}
}
class Bar {}
class Baz {
public $name;
function __construct($name)
{
$this->name = $name;
}
}
$container = new Container([
'foo' => [
'class' => '_\Foo',
'arguments' => [['ref' => 'bar']],
],
'bar' => [
'class' => '_\Bar',
],
'baz' => [
'class' => '_\Baz',
'arguments' => [['value' => 'baz']],
],
]);
var_dump($container->get('foo'));
var_dump($container->get('bar'));
var_dump($container->get('baz'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment