symfony7下关于HasLifecycleCallbacks的使用
在 Symfony 7 中,#[ORM\HasLifecycleCallbacks] 是 Doctrine ORM 提供的一个 PHP 8+ 属性(attribute),用于声明该实体类(如 CustomRegistrationOrder)包含生命周期回调方法(如 prePersist, postPersist 等)。这个属性的作用是告诉 Doctrine 要扫描这个类中带有生命周期钩子注解的方法,并在相应事件触发时自动调用它们。
例子:
use Doctrine\ORM\Mapping as ORM;
#[ORM\Table("custom_registration_orders")]
#[ORM\HasLifecycleCallbacks]
class CustomRegistrationOrder
{
#[ORM\Column(name: 'created_at', type: 'datetime', nullable: false)]
protected \DateTime $createdAt;
#[ORM\Column(name: 'updated_at', type: 'datetime', nullable: false)]
protected \DateTime $updatedAt;
#[ORM\PrePersist]
public function updateTimestamps(): void
{
$this->createdAt = new \DateTime();
$this->updatedAt = new \DateTime();
}
}
