使用 Doctrine 的 Entity Framework ,假设您有一个名为 $user
的实体,它与 $address
实体具有 OneToOne 关联。城市存储在地址实体中,而不是用户实体中。
据我所知,您可以像这样访问关联实体的值:
$user_city = &$user->getAddress()->getCity();
引用:http://symfony.com/doc/current/book/doctrine.html#fetching-related-objects
如果您需要在代码中多次访问用户的城市,是否最好将此值分配给变量(如上面带或不带&符号引用)?或者最好每次都通过整个链 $user->getAddress()->getCity()
调用实体值?
第一次调用后,$user->getAddress()
是否存储在 $user 实体中,因此从现在开始可以访问它的所有属性,而无需任何开销?
标准做法是什么?从长远来看哪种做法最有效?
最佳答案
如果$address
是一个单独的实体,则意味着它有自己的生命周期,无论您是否将其保存在单独的变量中,Doctrine都会正确处理对其的所有操作。 Doctrine 使用一种称为 Identity Map 的设计模式(更多信息请参见: http://docs.doctrine-project.org/en/2.0.x/reference/working-with-objects.html ),它保证您在显式克隆
它之前,它将始终返回相同的对象。从该链接:
In this case the Article is accessed from the entity manager twice, but modified in between. Doctrine 2 realizes this and will only ever give you access to one instance of the Article with ID 1234, no matter how often do you retrieve it from the EntityManager and even no matter what kind of Query method you are using (find, Repository Finder or DQL). This is called “Identity Map” pattern, which means Doctrine keeps a map of each entity and ids that have been retrieved per PHP request and keeps returning you the same instances.
至于“最佳实践”,适用软件设计法则。如果您只需要地址,则仅传递地址对象。如果您对整个用户进行操作,请传递用户对象。遵循依赖注入(inject)
和Demeter法则
原则,你会做得很好。
此外,这里不需要 &
运算符,因为 PHP 中的所有对象都是通过引用传递的。
关于symfony - 在 Symfony2 中访问关联实体的值的最佳实践是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23120673/