ORM's events provide powerful extension points.

Model & Repository events#

To subscribe to an event, add a new callback as a new array item.

Callback registration Callback signature
$onFlush function (IEntity[] $persisted, IEntity[] $removed) {}
$onBeforePersist function (IEntity $entity) {}
$onAfterPersist function (IEntity $entity) {}
$onBeforeInsert function (IEntity $entity) {}
$onAfterInsert function (IEntity $entity) {}
$onBeforeUpdate function (IEntity $entity) {}
$onAfterUpdate function (IEntity $entity) {}
$onBeforeRemove function (IEntity $entity) {}
$onAfterRemove function (IEntity $entity) {}
$onFlush function (IEntity[] $persisted, IEntity[] $removed) {}
$orm->books->onBeforeInsert[] = function (Book $book) {
    echo "Inserting into DB " . $book->title;
Entity events#

You may react on events also inside your entity. To implement your code, override event method. Do not forget to call parent's implementation!

Method signature Description
onCreate() When new entity is created. (ie. onLoad is not called)
onLoad(array $data) When entity is loaded from DB. (ie. onCreate is not called)
onRefresh(array $data, bool $isPartial = true) When entity is refreshed from DB by a persist call.
onFree() When all entites of model are destroyed.
onAttach(IRepository $r, EntityMetadata $m) When attached to repository.
onDetach() When detached from repository.
onPersist(mixed $id) When inserted/updated.
onBeforePersist() Before insert/update.
onAfterPersist() After insert/update.
onBeforeInsert() Before insert.
onAfterInsert() After insert.
onBeforeUpdate() Before update.
onAfterUpdate() After update.
onBeforeRemove() Before remove.
onAfterRemove() After remove.
 * @property int               $id        {primary}
 * @property DateTimeImmutable $createdAt
class Book extends Nextras\Orm\Entity\Entity
    public function onCreate()
        $this->createdAt = new DateTimeImmutable();