Doctrine 2 LifecycleCallbacks与抽象基类不被调用 [英] Doctrine 2 LifecycleCallbacks with abstract base class are not called

查看:68
本文介绍了Doctrine 2 LifecycleCallbacks与抽象基类不被调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种情况:

抽象类:


Abstract Class:

abstract class AbstractBase
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     * @var integer
     */
    protected $id;

    /**
     * @ORM\Column(type="datetime", name="updated_at")
     * @var \DateTime $updatedAt
     */
    protected $updatedAt;

    /**
     * @ORM\PreUpdate
     */
    public function setUpdatedAt()
    {
        die('THIS POINT IS NEVER REACHED');
        $this->updatedAt = new \DateTime();
    }
}

混凝土类:


Concrete Class:

/**
 * @ORM\Entity(repositoryClass="Entity\Repository\UserRepository")
 * @ORM\Table(name="users")
 * @ORM\HasLifecycleCallbacks
 */
class User extends AbstractBase
{
    // some fields, relations and setters/getters defined here, these all work as expected.
}

然后我在我的控制器中调用它:

Then i call it in my controller like this:

$user = $this->em->find('Entity\User', 1);
// i call some setters here like $user->setName('asd');
$this->em->flush();
die('end');

一切都按预期工作,所以抽象类的id字段为User实体创建,可以访问它等
问题是,从来没有达到die('这个要点永远不会)的行。 (注意@ ORM\PreUpdate)这意味着在
继承的对象上不调用lifecycleCallbacks。这是一个错误,还是有原因?

Everything works as expected, so the id field from the abstract class gets created for the User entity, i can access it etc. The problem is, that the line "die('THIS POINT IS NEVER REACHED')" is never reached. (Note the @ORM\PreUpdate) This means that lifecycleCallbacks are not called on inherited objects. Is this a bug, or is there a reason for this?

推荐答案

您的抽象基类必须被标记为映射超类,并包含 HasLifecycleCallbacks -Annotation。

Your abstract base class has to be anotated as Mapped Superclasses and include the HasLifecycleCallbacks-Annotation.

更多信息:原则文档中的继承映射

/**
 * @ORM\MappedSuperclass
 * @ORM\HasLifecycleCallbacks
 */
abstract class AbstractBase
{
    [...]

    /**
     * @ORM\PreUpdate
     */
    public function setUpdatedAt()
    {
        $this->updatedAt = new \DateTime();
    }
}

/**
 * @ORM\Entity(repositoryClass="Entity\Repository\UserRepository")
 * @ORM\Table(name="users")
 */
class User extends AbstractBase
{
    // some fields, relations and setters/getters defined here, these all work as expected.
}

这篇关于Doctrine 2 LifecycleCallbacks与抽象基类不被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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