Dependency Injection: What point am I allowed to create a new object?
        Posted  
        
            by 
                Gaz_Edge
            
        on Programmers
        
        See other posts from Programmers
        
            or by Gaz_Edge
        
        
        
        Published on 2013-10-31T18:14:17Z
        Indexed on 
            2013/10/31
            22:17 UTC
        
        
        Read the original article
        Hit count: 198
        
php
|dependency-injection
I am refactoring a php application and I am trying to do has much dependency injection 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.
Im 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 i.e. use the dreaded new keyword.
The problem I have now run into is at what point can I actually create new objects? Its 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 factory pattern and DI, or am I going way off the mark here.
© Programmers or respective owner