Circular dependency - Injecting objects that are directly depended on each other

后端 未结 2 1730
刺人心
刺人心 2021-01-11 13:57

I have used Dice PHP DI container for quite a while and it seems the best in terms of simplicity of injecting dependencies.

From Dice Documentation:

cl         


        
2条回答
  •  独厮守ぢ
    2021-01-11 14:35

    You have a circular dependency, which is very hard to solve. The first thing to do is to try to get rid of this circular dependency by refactoring your classes and how they interact.

    If you really can't manage to do it, there are solutions. I'll copy-paste my answer from Self-referencing models cause Maximum function nesting level of x in Laravel 4:

    • Setter injection

    Rather than injecting a dependency in the constructor, you can have it injected in a setter, which would be called after the object is constructed. In pseudo-code, that would look like that:

    $userRepo = new UserRepository();
    $cartRepo = new CartRepository($userRepo);
    $userRepo->setCartRepo($userRepo);
    
    • Lazy injection

    I don't know if Dice does support lazy injection, but that's also a solution: the container will inject a proxy object instead of the actual dependency. That proxy-object will load the dependency only when it is accessed, thus removing the need to build the dependency when the constructor is called.

    Here is an explanation on how lazy injection works if you are interested: http://php-di.org/doc/lazy-injection.html

提交回复
热议问题