
Originally Posted by
Dr Livingston
Is there a solution that isn't bloated and at the same time, light weight?
Here's something I whipped up in about 10 minutes
PHP Code:
class Injector {
private $services;
public function __construct() {
$this->services = array();
}
public function register($service_name, $class, $args = null) {
if (is_null($args)) {
$args = array();
}
if (!class_exists($class)) {
throw new Exception('The class '.$class.' does not exist');
}
$this->services[$service_name] = array($class, $args);
}
public function get($service_name) {
if (!isset($this->services[$service_name])) {
throw new Exception($service_name.' is not a registered service');
}
list($class, $dependencies) = $this->services[$service_name];
$arguments = array();
foreach($dependencies as $dependency) {
$arguments[] = $this->get($dependency);
}
$reflection = new ReflectionClass($class);
return $reflection->newInstanceArgs($arguments);
}
}
class Foo {
function __construct() {
}
}
class Bar {
var $foo;
function __construct($foo) {
$this->foo = $foo;
}
}
$injector = new Injector();
$injector->register('foo', 'foo');
$injector->register('bar', 'bar', array('foo'));
$bar = $injector->get('bar');
assert(is_a($bar, 'bar'));
assert(is_a($bar->foo, 'foo'));
That's about as lightweight as you can get. Obviously there's functionality missing, but that could be added as needed.
Now, there's still the question of why you'd use something like this instead of simply wiring them together manually. It's hard to see the benefit with such a trivial example, but I think with a large object graph it makes things easier to maintain by cutting down the boiler plate and centralizing configuration.
Bookmarks