Dependency Injection - How much to inject?

Hey Guys.

Consider this situation: There is one class which deals with the application as a whole. An object of this class contains a database object, an object containing settings and an object containing form data:

class Application{
    public $Database;
    public $Settings;
    public $Input;
}

Any class which would require access to this database would access it through the application object it stems from.

Say I have a mapper which purely uses the application’s database connection. Which would you advise - passing the application object, or passing the database object?

I.e:

interface iMapper{
    function __Construct(Application $A);
}

Or

interface iMapper{
    function __Construct(Database $D);
}

At current I can only see the mapper using the database connection, so I would think that passing the Database object alone would be enough… and yet my gut instinct is to pass the Application object.

Nice article, it certainly cleared up the benefits of passing the object directly. It would make testing more feasible by not requiring an application object.

Thanks all :slight_smile:

http://misko.hevery.com/2008/07/18/breaking-the-law-of-demeter-is-like-looking-for-a-needle-in-the-haystack/

Though you ask about “passing the application object, or passing the database object,” the real question is between passing a Registry containing the object or passing the object directly. The answer is – it depends. Part of the answer is style and consistency. A Registry is a consistent way to find common objects. If that consistency is useful in your application then it may make sense.

Don’t put the __constructor in an interface. This keeps the flexibility, which the dependency injection pattern takes care of.


class MapperA implements Mapper
{
       function __construct(Database $d) { ... }
}

However if another mapper requires another object, it is free to specify the dependency in the constructor, and the dependency injection pattern will ensure its satisfied.


class MapperB implements Mapper
{
       function __construct(Database $d, Settings $s) { ... }
}

Hi…

Pass only what you need.

yours, Marcus