I am interested in applying dependency injection to my current project, which makes use of the MVC pattern.
My controllers will call the models and therefore will need to inject the dependencies into the models. To do this, the controller must have the dependencies (such as a database object) in the first place. The controller doesn’t need to make use of some of these dependencies (such as the database object), so I feel that it shouldn’t be given this dependency. However, it has to have these dependencies if it is to inject them into the model objects.
How can I avoid having dependencies injected into an object just so that it can pass them on? Doing so feels wrong and can result in many dependencies being injected into an object.
Edit: I am using PHP.
I agree with your concerns. It’s a code smell to take dependencies for the sole purpose of passing them on to other dependencies.
Depending on the exact interaction between those dependencies, you have a couple of options:
If only one instance of the dependency is needed
If your Controller only needs a single instance of a dependency, then just take a dependency on that instead.
(apologies for the c# code)
Don’t do this:
Instead, you can do this:
You may want to consider
MyDependencybehind an interface itself. See also Refactoring to Aggregate Services.If you need to create multiple instances during the Controller’s lifetime
Sometimes, however, you need to create multiple instances dynamically. This is often the case when you need a value that’s only available at run-time before you can fully populate a dependency.
In this case, an Abstract Factory is an excellent and universal solution.