自引用模型导致Laravel 4中x的最大函数嵌套级别 [英] Self-referencing models cause Maximum function nesting level of x in Laravel 4

查看:60
本文介绍了自引用模型导致Laravel 4中x的最大函数嵌套级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个相当大的Laravel项目,并且正在使用存储库.

I'm working on a reasonably large Laravel project and am using Repositories.

我有一个用户存储库,它像这样注入其依赖项:

I have a user repository which injects its dependencies like so:

public function __construct(CartRepository $cartRepo...)

这会导致以下错误:

Maximum function nesting level of '100' reached, aborting!

我认为这是因为CartRepo注入了ItemRepo,后者又注入了UserRepo,从而导致了无限的嵌套循环.

I think this is because the CartRepo injects an ItemRepo which in turn injects the UserRepo, causing an infinite nesting loop.

我不知道如何解决这个问题,因为项目绑定到用户时,ItemRepo需要UserRepo?

What I don't get is how to find away around this, the ItemRepo needs the UserRepo as items are tied to a user?

有没有人遇到过这个?如果是这样,您如何解决呢?

Has anyone come across this before? If so how'd you get around it?

我知道我可以增加xdebug.max_nesting_level,但是即使将其值设为750,它仍然会引发错误,我宁愿解决根本的问题,也不仅仅是将其掩埋.

I know I can increase xdebug.max_nesting_level but even with a value of 750 it's still throwing an error, I'd also rather fix the underlying problem than just bury it.

推荐答案

您的依存关系图中有一个循环:

You have a cycle in your dependency graph:

UserRepo -> CartRepo -> ItemRepo -> UserRepo -> …

您无法解决该问题.这是一个无限循环,xdebug.max_nesting_level对您无济于事.

You can't resolve that. It's an infinite loop, xdebug.max_nesting_level won't help you.

我很惊讶Laravel DI容器没有抛出明确的异常.

I'm just surprised that Laravel DI container doesn't throw an explicit exception.

您必须重新考虑服务/存储库之间的依赖关系,也许是通过将一些类拆分为较小的,耦合较少的对象来实现的.

You have to rethink your dependencies between services/repositories, maybe by splitting some classes into smaller, less coupled objects.

更新:糟糕,我忘记了几种解决方案!

Update: Woops, I forgot about a couple of solutions!

  • 固定注射

您可以将其注入设置器中,而不是在构造函数中注入依赖项,后者将在构造对象之后调用.用伪代码,看起来像这样:

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);

  • 懒惰注射
  • 我不知道Laravel是否支持延迟注入,但这也是一个解决方案:容器将注入代理对象而不是实际的依赖项.该代理对象仅在被访问时才加载依赖项,从而消除了在调用构造函数时构建依赖项的需要.

    I don't know if Laravel 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.

    这篇关于自引用模型导致Laravel 4中x的最大函数嵌套级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆