PHP Dependency Injection – When to Create a New Object

dependency-injectionPHP

I am refactoring a PHP application, and I am trying to do has much dependency injection (DI) as possible.

I feel like I've got a good grasp of how it works, and I can certainly see my classes becoming a lot leaner and more robust.

I'm refactoring so that I can inject a dependency rather than create a new object within the class, but at some point I am going to have to create some objects, that is, use the dreaded new keyword.

The problem I have now run into is at what point can I actually create new objects? It's looking like I'll end up at a top level class, creating loads of new objects as there is no where else to go. This feels wrong.

I've read some blogs that use factory classes to create all the objects, and then you inject the factory into other classes. You can then call the factory methods, and the factory creates the new object for you.

My concern with doing this is now my factory classes are going to be a new free-for-all! I guess this may be OK as they are factory classes, but are there some rules to stick to when using a factory pattern and DI, or am I going way off the mark here?

Best Answer

After quite a bit of googling around for this, it seems like (as mentioned in a comment above) the top level class I was talking about is called the Composition Root.

It does indeed seem to be the accepted solution to add the creation of all objects within this Composition Root (or referencing an IoC container from here).

My original concern with this was that this top level class would end up being a bit of a mess. This is true to some extent, but the pros out weigh the cons. For example I can see the readability, testability and maintainability of all my other classes has improved.

The top level class may be a bit messy, littered with new and set_property() but I have to say I actually prefer having all this code in one place, rather than scattered about all over the other classes

Another useful page discussing performance hits of this method here