It's my first time on StackOverflow and I hope my question isn't that noobish! I never actually tried to resolve this, I always used instead DI via setters methods instead of constructor, but It's now time to look for a better pattern! :) I tried to perform a search but I couldn't get any satisfying answer :(
Basically I have a container class that is supposed to link all the dependencies together, and every of those classes (A, B, ...) should be able to access from "their inside" other classes in the container as well.
<?php
class MyContainer
{
function __construct(A $a, B $b){
$this->a = $a;
$this->b = $b;
}
function getA(){ return $this->a; }
function getB(){ return $this->b; }
}
class A
{
function __construct(MyContainer $myc){ $this->myc = $myc; }
function useA(){ echo "A"; $this->myc->getB()->doSmt(); }
function doSmt(){ echo "A smt"; }
}
class B
{
function __construct(MyContainer $myc){ $this->myc = $myc; }
function useB(){ echo "B"; $this->myc->getA()->doSmt(); }
function doSmt(){ echo "B smt"; }
}
?>
Now that is impossible to instantiate, because MYC requires A and B, and A and B require MYC.
How can I resolve this? My professor told me that when you came into a circular dependency more than likely it's a design problem. But I can't figure out how to do it the correct way: the existence of A and B actually depends on MyCollection and vice versa.
P.S. I want to try to resolve this using DI, if it can be done in a clean and sensible way. I'm not a fan of factories! :)
Thank you in advance for your help!