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
    You have a class that is doing more than one thing. Split it up. Aug 13, 2013 at 21:06
  • 1
    While I agree with the accepted answer, the occasional unused dependency should be fine, since you should not be doing any work in your constructors. Nov 6, 2013 at 1:48

1 Answer 1


Here are the three solutions I typically evaluate on a case-by-case basis:

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

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

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

  • I strongly vote for #3. The "Sometimes I don't need the dependency" deal screams out for separate classes, as clearly this class isn't following the Single Responsibility Principle. Aug 13, 2013 at 21:06
  • Yes my class is doing too much... I will got with #2 and #3. Now that I think of it I can separate in 2 classes. Aug 13, 2013 at 21:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.