Dependency Hell — how does one pass dependencies to deeply nested objects?

It’s a common misconception that dependencies need to be passed through the object graph. To summarize the example Miško Hevery gives in Clean Code: Don’t look for things, a House that needs a Door, doesnt need to know about the Lock in the Door:

class HouseBuilder
{
    public function buildHouse()
    {
        $lock  = new Lock;
        $door  = new Door($lock);
        $house = new House($door);

        return $house;
    }
}

As you can see, House is completely oblivious of the fact that the Door in it requires a lock. It’s the responsibility of the HouseBuilder to create all the required dependencies and stack them together as they are needed. From the inside out.

Consequently, in your scenario you have to identify which objects should operate on which dependencies (cf Law of Demeter). Your Builder then has to create all collaborators and make sure the dependencies are injected into the appropriate objects.

Also see How to Think About the “new” Operator with Respect to Unit Testing

Leave a Comment