I’m not usually one to release code into the wild but here’s something which is both mature and unique enough to be worthwhile.
Dice is a Convention-Over-Configuration Dependency Injection Container I’ve been working on. At its most basic level and with zero configuration it lets you build an object graph with little effort:
class A {
private $b;
public function __construct(B $b) {
$this->b = $b;
}
}
class B {
private $c,$d;
public function __construct(C $c, D $d) {
$this->c = $c;
$this->d = $d;
}
}
class C {
}
class D {
private $e;
public function __construct(E $e) {
$this->e = $e;
}
}
class E {
}
$dice = new Injection;
$a = $dice->create('a');
print_r($a);
Which will output:
A Object
(
[b:A:private] => B Object
(
[c:B:private] => C Object
(
)
[d:B:private] => D Object
(
[e:D:private] => E Object
(
)
)
)
)
As a practical example with a minimal configuration it allows you to do this:
//Firstly create a rule
$rule = new DiceRule;
$rule->shared = true;
//PDO will be constructed by the container with these parameters:
$rule->constructParams = array('mysql:host=127.0.0.1;dbname=mydb', 'username', 'password');
$dice->addRule('PDO', $rule);
$pdo = $dice->create('PDO');
$pdo2 = $dice->create('PDO');
var_dump($pdo === $pdo2); //TRUE
//And any class which asks for an instance of PDO will be given the same instance:
class MyClass {
public $pdo;
public function __construct(PDO $pdo) {
$this->pdo = $pdo;
}
}
$myobj = $dice->create('MyClass');
var_dump($pdo === $myobj->pdo);
You would be able to define any class in the system with a dependency on PDO and it would be passed the shared instance of the PDO object on creation. This goes for a class which is any depth down the object graph:
class MyApplication {
public function __construct(MyController $controller) {
}
}
class MyController {
public function __construct(PDO $pdo) {
}
}
$dice->create('MyApplication');
In this scenario, “MyController” would still be passed the shared instance of PDO when it was created.
One important distinction that Dice makes is many other Dependency Injection Containers is that it doesn’t need any metadata about most of the classes it’s creating. Only those which have special rules such as being shared across the application
Any comments/suggestions?
Yes, the temptation to call it TinyDIC or something was large but I thought I’d keep it serious because its uses are far fetched.