Last active
December 23, 2015 00:59
-
-
Save igorw/6557390 to your computer and use it in GitHub Desktop.
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 | |
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