gpt4 book ai didi

symfony - prePersist 和构造方法之间的 Doctrine 差异

转载 作者:行者123 更新时间:2023-12-02 03:25:42 26 4
gpt4 key购买 nike

根据doctrine documentary :

The prePersist event occurs for a given entity before the respective EntityManager persist operation for that entity is executed. It should be noted that this event is only triggered on initial persist of an entity (i.e. it does not trigger on future updates).

最后一部分很重要,让我想知道;在这种情况下与 __contruct() 方法有什么不同吗?

假设我想设置实体的创建日期和时间 (createdAt)。我可以通过生命周期回调来做到这一点:

/**
* @ORM\PrePersist
*/
public function setTimestamp()
{
$this->setCreatedAt(new \DateTime('now'));
}

或者我可以像这样使用构造函数:

public function __construct()
{
$this->createdAt = new \DateTime('now');
}

这完全一样吗?如果是这样,为什么会有 PrePersist 生命周期回调?

最佳答案

Does this do exactly the same?

不!它们在语义上是不同的。

  • 当您在内存中创建对象时,会调用构造函数方法。
  • prePersist 事件在将其持久保存到数据库之前触发。

考虑一种情况,您创建对象并处理一些数据(这将需要一段时间),然后将其保存到数据库中。所以时间可能会有所不同。

关于symfony - prePersist 和构造方法之间的 Doctrine 差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53519543/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com