AdamGold
AdamGold

Reputation: 5051

PHP Dependency Injection - 2 classes contain each other

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?

Upvotes: 0

Views: 452

Answers (1)

Peter Uhnak
Peter Uhnak

Reputation: 10217

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.

Upvotes: 2

Related Questions