1

I have 2 classes - UserService and ProfileService. I need each class to contain the other one. I am trying to do this with dependency injection:

$this->container['userService'] = function ($c) {
    return new UserService($c['profileService']);
};

$this->container['profileService'] = function ($c) {
    return new ProfileService($c['userService']);
};

In each class I define a constructor to handle these parameters. Anyway, I am getting a "ERR_EMPTY_RESPONSE" error in Chrome. What's the right way to do this?

4
  • Looks like you have to structure your classes differently, so that you don't have that kind of hen-egg-problem. Commented Oct 25, 2015 at 15:49
  • Do you have a better structure in mind? Commented Oct 25, 2015 at 15:54
  • Not with that little information. Why do those classes each need a factory function for the respective other class provided on construction time? Commented Oct 25, 2015 at 15:55
  • also are you using some particular DI framework? Commented Oct 25, 2015 at 20:28

1 Answer 1

3

Circular dependencies are in most cases sign of a bad design. It means that the two classes are very tightly coupled together which often implies mixing of concerns.

enter image description here

Instead of trying to force this to work, try to find out why there is such dependency --- why does one class need the other (and vice versa)? And is that part really related to a particular side of the problem?

Once the dependency understood, the solution usually is to extract the infringing part into third (or fourth) class and let both the classes refer to that, instead of referring to each other.

enter image description here

Of course knowing more about your particular problem would also enable me to give you a better answer.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.