I have a class that has 3 dependencies.
WritabbleDBConnection, ReadOnlyDBConnection and a QueryFilter utility object.
I want to do constructor Injection so my class would look something like this.
class PersonDataAccessObject {
public function __construct($dbWrite, $dbRead, $queryFilter) {
// sets to local vars
}
public function A() {} // uses $dbRead
public function B() {} // uses $dbWrite
}
This object would most likely be instantiated in a static factory, which knows how to retrieve the DB connections.
The problem I see is every time I build this object I need to pass all 3 dependencies although possibly only one of the will be used for the operations I will need to do.
I don’t like hiding my dependencies inside a service locator class, since I want to keep my dependencies explicit.
Are there any solutions for this? Or do I have to live with unused instances?
2
Here are the three solutions I typically evaluate on a case-by-case basis:
-
Use a Container or service locator. This is the fastest because you can lazy-load the dependencies and only call what is needed. However, you lose a lot of testability and your code becomes dependent on something it shouldn’t care about.
-
Pass all dependencies in. This is more proper than the above, but you lose a bit of efficiency for the sake of more-clear programming.
-
Split your class so each of your methods actually require all of the dependencies. In a lot of cases, this is the most pure way of doing things, but unfortunately it can easily get into overkill mode. Not sure if this is measurable or relevant, but I’m typically the happiest when I’m able to go this route.
I typically go with #2 or #3, unless it’s absolutely necessary I need access to a container. This is sometimes okay for framework-level code, but should be avoided in your application code.
2