Skip to content

Lifecycle hooks and bulk operations

An entity opts into lifecycle callbacks by implementing one or more interfaces:

  • OnNewInterface and OnLoadInterface;
  • BeforePersistInterface and AfterPersistInterface;
  • BeforeInsertInterface and AfterInsertInterface;
  • BeforeUpdateInterface and AfterUpdateInterface;
  • BeforeDeleteInterface and AfterDeleteInterface.
use Small\SwooleEntityManager\Entity\Contract\BeforePersistInterface;
use Small\SwooleEntityManager\Entity\Contract\OnNewInterface;

final class UserEntity extends AbstractEntity implements OnNewInterface, BeforePersistInterface
{
    public function onNew(): void
    {
        $this->createdAt = new \DateTimeImmutable();
    }

    public function beforePersist(): void
    {
        $this->updatedAt = new \DateTimeImmutable();
    }
}

Execution order for a new entity is:

  1. beforePersist();
  2. beforeInsert();
  3. database insert;
  4. afterInsert();
  5. afterPersist().

For a loaded entity, update hooks replace insert hooks. Delete uses only delete hooks.

newEntity() invokes onNew() when implemented. Hydration invokes onLoad().

Set-based executeUpdate() and executeDelete() skip callbacks by default. Pass skipTriggers: false to select and process matching entities one by one.

Next chapter: Swoole runtime and connection drivers