خطافات دورة الحياة
Weaver ORM provides a set of PHP 8 attributes that let you attach callbacks directly to entity methods. These callbacks are invoked at specific points in the entity's persistence lifecycle — before or after insert, update, delete, and load operations.
Lifecycle attributes
Attach these attributes to instance methods of your entity class. The method receives no arguments unless stated otherwise.
#[BeforeAdd] — before INSERT
Called immediately before the entity is inserted into the database (replaces Doctrine's #[PrePersist]).
<?php
namespace App\Entity;
use Weaver\ORM\Lifecycle\BeforeAdd;
class User
{
public string $passwordHash = '';
private string $plainPassword = '';
#[BeforeAdd]
public function hashPassword(): void
{
if ($this->plainPassword !== '') {
$this->passwordHash = password_hash($this->plainPassword, PASSWORD_BCRYPT);
$this->plainPassword = '';
}
}
}
#[AfterAdd] — after INSERT
Called after the INSERT statement has been executed and the generated primary key has been assigned (replaces Doctrine's #[PostPersist]).
<?php
use Weaver\ORM\Lifecycle\AfterAdd;
class Order
{
public ?int $id = null;
#[AfterAdd]
public function generateConfirmationNumber(): void
{
// $this->id is now available
$this->confirmationNumber = sprintf('ORD-%08d', $this->id);
}
}
#[BeforeUpdate] — before UPDATE
Called before the UPDATE statement for a dirty entity.
<?php
use Weaver\ORM\Lifecycle\BeforeUpdate;
class Article
{
public ?\DateTimeImmutable $updatedAt = null;
#[BeforeUpdate]
public function touchTimestamp(): void
{
$this->updatedAt = new \DateTimeImmutable();
}
}
#[AfterUpdate] — after UPDATE
Called after the UPDATE statement completes.
<?php
use Weaver\ORM\Lifecycle\AfterUpdate;
class Product
{
#[AfterUpdate]
public function clearPricingCache(): void
{
// Invalidate any cached pricing computed from this entity
}
}