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.
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.