Doctrine2 __constructor在使用$ em-> find()时不调用; ?如何正确加载实体? [英] Doctrine2 __constructor not called when using $em->find(); ? How to load entity properly?

查看:87
本文介绍了Doctrine2 __constructor在使用$ em-> find()时不调用; ?如何正确加载实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习doctrine2,并且有一个问题,如何自动调用构造函数。
例如,在我的实体我有

I'm learning doctrine2, and having a problem how to call constructor automatically. For example, in my entity I have

/**
 * @Entity
 */
class User{
   ....
   public function __construct() {
       exit('in');
   }
}

当我以这种方式获取对象时: p>

and when I get the object this way:

$userObj = $em->find('User', 1);

我从数据库中获取该对象,但构造函数从不被调用。
我想把一些常见的东西放在构造函数中,比如验证规则,甚至把这些原则文档中的示例代码,如

I do get that object from database, but constructor is never called. I want to put some common things in constructor, like validation rules, or even to put sample code from the doctrine documentation like

        $this->comments = new ArrayCollection();

当您在代码中创建新对象(如

This ofcourse works when I create new object in code for creating a user like

$user = new User(); //now constructor works just fine

现在,获取实体的正确方式是什么?我怀疑我每次用户$ em-> find()与$ user0bj - > __ construct()时手动调用构造函数; ?这会有点吸引...或者我应该使用其他的东西 - > find()来获得单一的实体正确?
我知道我可以使用@PrePersist,我正在使用它来实际执行验证检查等。
我猜这可能是在这里遗漏的东西,或者我试图使用一个穷人的构造函数办法。感谢任何解释和指导!

Now, what is the "proper" way of getting the entity? I doubt I have to call constructor manually each time I user $em->find() with $user0bj->__construct(); ? This would kinda sucks then... Or I should use something other then ->find() to get single entity properly? I know I can user @PrePersist, and I am using it to actually do validation checks etc. I guess that I'm probably missing something here, or I'm trying to use constructor in a poor way. Thanks for any explanations and guides!

推荐答案

我确定找到或类似的情况不会调用构造函数...

I'm pretty certain that find or similar isn't expected to call the constructor...

您需要挂钩到 @ PostLoad 事件。

这篇关于Doctrine2 __constructor在使用$ em-> find()时不调用; ?如何正确加载实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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