Reputation: 259
I have a very small app which i am using to learn design patterns.
Currently I am trying to implement a dependcy injection container but it just feels like a factory.
Can someone explain what is wrong with the container and where it can be improved.
As i said its very minimal and the app only requires a couple of objects:
class MyContainer
{
public function getObjectA()
{
return new MyObjectA();
}
public function getObjectB()
{
$objectBArrayParam = array('arrparam1','arrparam2', 'arrparam3', 'arrparam4');
$objectB = new MyObjectB('param1','param2', 'param3', 'param4', $objectBArrayParam);
return $objectB;
}
public function getApplicationRunner()
{
$objectA = $this->getObjectA();
$objectB = $this->getObjectB();
$app = new ApplicationRunner($obejctA, $objectB);
return $app;
}
}
Upvotes: 4
Views: 44
Reputation: 39888
A factory could be seen as a static type of Dependency Injection. You're specifying the arguments at compile time and the resulting object graph is always the same.
A dependency injection tool would use some kind of reflection to check at runtime what arguments are needed. Then it would search for the required types in its configuration and construct the object graph for you.
If you want to build a simple DI container you need to create support for registering types and for checking required types at runtime.
Something like:
myDi.Register(<typeofIObectA>).To(<typeofobjectA>)
myDi.Register(<typeofIObjectB>).To(<typeofobjectB>)
MyDi.Resolve(<typofApplicationRunner>)
The DI container would see that ApplicationRunner needs two arguments. It would check the configuration for those types and thn construct the objects.
Upvotes: 1