I want to make fields updated_at
and created_at
in my Doctrine entities to update automatically.
In Ruby on Rails models there
You can implement it as a trait as well - like this:
createdAt ?? new DateTime();
}
/**
* @param DateTimeInterface $createdAt
* @return $this
*/
public function setCreatedAt(DateTimeInterface $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
/**
* @return DateTimeInterface|null
*/
public function getUpdatedAt(): ?DateTimeInterface
{
return $this->updatedAt ?? new DateTime();
}
/**
* @param DateTimeInterface $updatedAt
* @return $this
*/
public function setUpdatedAt(DateTimeInterface $updatedAt): self
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* @ORM\PrePersist()
* @ORM\PreUpdate()
*/
public function updateTimestamps(): void
{
$now = new DateTime();
$this->setUpdatedAt($now);
if ($this->getId() === null) {
$this->setCreatedAt($now);
}
}
}
Add this trait to your entity (and don't forget @ORM\HasLifecycleCallbacks()
notation):