带有 Symfony DI 容器的 Doctrine 2 [英] Doctrine 2 with Symfony DI Container

查看:33
本文介绍了带有 Symfony DI 容器的 Doctrine 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个利用 Doctrine 2 的 Zend Framework 项目.我也在尝试让 Symfony 的 DI 容器与该项目一起工作,但我遇到了问题.假设我有一个需要注入两个实例的Foo"类.我可以设置一个 Symfony DI 容器来获取注入依赖项的新Foo"没有问题.伟大的!但是现在如果我想让Foo"成为 Doctrine 实体怎么办?当我将实体插入数据库时​​一切正常,因为我可以从 DI 容器中获取一个新的实体并简单地保留实体.但是,当我从 DB Doctrine 查询实体时,正在实例化我的Foo"实例,并且它们不会注入正确的依赖项.如何让 Doctrine 使用我的 DI 容器,以便实体具有适当的依赖关系?我知道 Doctrine 提供了一个postLoad"钩子,我可以用它来向我的实体注入依赖项,但这种方式违背了 DI 容器的目的和好处.

I am working on a Zend Framework project that leverages Doctrine 2. I'm trying to get Symfony's DI container working with the project as well, but I'm having trouble. Suppose I have a class "Foo" that needs two instances injected. I can set up a Symfony DI container no problem to fetch me a new "Foo" with the dependencies injected. Great! But now what if I want to make "Foo" a Doctrine entity? All is well when I insert the entity to the DB because I can grab a new one from the DI container and simply persist the entity. However, when I query the entity from the DB Doctrine is instantiating my "Foo" instances and they will not have the proper dependencies injected. How do I get Doctrine to use my DI container so that the entity will have the appropriate dependencies? I know that Doctrine offers a "postLoad" hook in that I could use to inject dependencies on my entity, but that kind of defeats the purpose and benefit of the DI container.

推荐答案

Doctrine Entity 是可更新的,而不是可注入的.不应通过 DIC 创建实体.请参阅以下有关可更新和可注入之间区别的博文:

A Doctrine Entity is a newable, not an injectable. Entities are not supposed to be created through a DIC. See this following blog post on the difference between newable and injectable:

http://misko.hevery.com/2008/09/30/to-new-or-not-to-new/

这篇关于带有 Symfony DI 容器的 Doctrine 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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