According to the 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).
The last part is important and makes me wonder; is there a difference in that case with the __contruct() method?
Let's say I want to set the creation date and time (createdAt) for an enitity. I can do this with the lifecycle callback:
/**
* @ORM\PrePersist
*/
public function setTimestamp()
{
$this->setCreatedAt(new \DateTime('now'));
}
Run Code Online (Sandbox Code Playgroud)
Or I can use the contructor like this:
public function __construct()
{
$this->createdAt = new \DateTime('now');
}
Run Code Online (Sandbox Code Playgroud)
Does this do exactly the same? And if so, why is there the PrePersist lifecycle callback?
这完全一样吗?
不!它们在语义上是不同的。
考虑这样一种情况,您创建对象并处理一些数据(这将需要一段时间),然后将其保存到数据库中。所以时间可能会有所不同。
| 归档时间: |
|
| 查看次数: |
498 次 |
| 最近记录: |