Question

I've been reading up on dependency injection and I think I pretty much understand the concepts, including constructor injection and setter injection.

However, I am unsure what I would do in the following scenario:

Say I have a class that has many methods, but only one of those methods requires a certain other object. How do I go about providing this object to the method? Should I not just directly pass the object to method as a parameter like so:

class aClass
{
    function aMethod(anotherClass $anotherClass)
    {
        anotherClass->hello();
    }

    function otherMethods()
    {
    }
    .....
}

The other option would be to provide it to the entire class, which seems unnecessary. like so:

class aClass
{
    protected $_anotherClass;

    function aMethod()
    {
        anotherClass->hello();
    }

    function otherMethods()
    {
    }
    .....

    function setAnotherClass(anotherClass $anotherClass)
    {
            $this->_anotherClass;
    }
}

When should I pass an object to a method and when should I use dependency injection via constructors/setters? Is there a rule of thumb or a best practice for when to use one of these two options?

Thanks for your help in advance.

Was it helpful?

Solution

You mentioned a rule of thumb, so here it is:

Ask yourself the question: could someone legitimately call this method twice on the same object, providing different values for the argument in the two calls?

If yes, then leave it as a parameter. If no, then it's a good candidate for injection as you describe.

This is a good example of a method of the first type, where removing the parameter and injecting a dependency in the class instead would be a really bad idea. C# instead of PHP, but you get the picture.

OTHER TIPS

The internal workings of a class are no-ones business but that class itself. If only one function requires the dependency then so be it.

Alternatively you could wonder why only one function has the dependency, is you class maybe doing two separate things?

The only reason you wouldn't want to inject dependencies in the constructor is when the cost of making that resource is very high (ready a large file on disk, connecting to remote host etc.), but even in that case, you could pass in a 'proxy' or 'deferred' object as a 'promise' that you can get to the dependency if you ever need it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top