How to avoid dependency injection into an object so that it can pass them?

I am interested in applying dependency injection to my current project that uses the MVC pattern.

My controllers will invoke models, and so you will have to inject dependencies into the models. For this, the controller must have dependencies (for example, a database object) in the first place. The controller does not need to use some of these dependencies (for example, a database object), so I feel that it should not be given this dependency. However, it must have these dependencies if it is to introduce them into model objects.

How can I avoid having dependencies injected into an object so that they can pass them? Doing this is wrong and can lead to many dependencies being injected into the object.

Edit: I am using PHP.

+5
source share
2 answers

I agree with your concerns. This is the smell of code for accepting dependencies for the sole purpose of passing them to other dependencies.

Depending on the exact interaction between these dependencies, you have several options:

If only one instance of the dependency is required

If your controller only needs one instance of the dependencies, then use the dependency instead.

(apologies for C # code)

Do not do this:

public class MyController
{
    public MyController(IDb db)
    {
        var dep = new MyDependency(db);
        // Use dep or save it for later
    }
}

Instead, you can do this:

public class MyController
{
    public MyController(MyDependency dep)
    {
        // Use dep or save it for later
    }
}

MyDependency . . .

, , . , , , .

Factory .

+2

PHP, (IOC).

question StackOverflow IOC PHP. IOC , , . ;)

, ? , .

, IOC void. , , . ( ) , . IOC , , , , .

+1

All Articles