---
title: 'Entity Lifecycle Event Subscriber'
url: 'http://phramecms.org/cookbook/entity-lifecycle-event-subscriber'
markdown_url: 'http://phramecms.org/cookbook/entity-lifecycle-event-subscriber.md'
bundle: recipe
category: events
difficulty: beginner
packages_used:
  - phramecms/core
  - phramecms/entity
  - phramecms/database
  - phramecms/config
summary: 'Subscribe to EntityPreSaveEvent, EntityPostSaveEvent, and EntityTransitionedEvent via phrame.event_subscriber while respecting PhrameCMS transaction and dry-run invariants.'
source: 'https://github.com/PhrameCMS/docs/blob/main/cookbook/entity-lifecycle-event-subscriber.md'
updated_at: '2026-12-04T21:49:38+00:00'
---

# Entity Lifecycle Event Subscriber

PhrameCMS dispatches strongly typed PSR-14 events across the entity lifecycle. This recipe implements a single `EventSubscriberInterface` (`phrame.event_subscriber`) that:

1. Auto-generates a URL `slug` and trims whitespace on `EntityPreSaveEvent` (**before** JSON Schema validation and **before** the database transaction).
2. Records a post-commit indexing notification on `EntityPostSaveEvent` (**strictly after** transaction commit).
3. Reacts when an article is published on `EntityTransitionedEvent` (`WorkflowState::Published`, also **strictly post-commit**).

---

## Key Invariants to Respect

Before writing listeners, keep these guaranteed `DatabaseEntityRepository` and `OperationBus` invariants in mind:

- **`EntityPreSaveEvent` (mutable `AlterEvent`)**: Fires after defaults/merges and **before** compiled bundle JSON Schema validation and `runInTransaction()`. Any fields you set or alter via `$event->setField()` are validated against the bundle schema and committed atomically. Throwing an exception aborts cleanly before any database write.
- **`EntityPostSaveEvent` and `EntityTransitionedEvent` (immutable `readonly`)**: Fire **strictly after** the database transaction commits, so webhooks, cache invalidation, and search-index updates never observe uncommitted or rolled-back writes.
- **Zero mutation events on `dry_run: true`**: `EntityCreateOperation`, `EntityUpdateOperation`, and `EntityTransitionOperation` preview changes without mutating `DatabaseEntityRepository` — none of the entity lifecycle events fire during dry-run previews or `proposal.create` staging.

---

## Step 1: Implement `EventSubscriberInterface`

Create `src/Event/ArticleLifecycleSubscriber.php`. Inject any side-effect collaborator (for example, a queue or search indexer interface) through the constructor so `ContainerBuilder::autowire()` wires it automatically:

```php
<?php

declare(strict_types=1);

namespace Acme\Editorial\Event;

use PhrameCms\Core\Contract\EventSubscriberInterface;
use PhrameCms\Core\Event\EventSubscription;
use PhrameCms\Entity\Event\EntityPostSaveEvent;
use PhrameCms\Entity\Event\EntityPreSaveEvent;
use PhrameCms\Entity\Event\EntityTransitionedEvent;
use PhrameCms\Entity\Workflow\WorkflowState;

final readonly class ArticleLifecycleSubscriber implements EventSubscriberInterface
{
    public function __construct(
        private SearchIndexBuffer $searchIndex,
    ) {}

    /** @return list<EventSubscription> */
    public function subscriptions(): array
    {
        return [
            new EventSubscription(EntityPreSaveEvent::class, 'onPreSave', priority: 20),
            new EventSubscription(EntityPostSaveEvent::class, 'onPostSave', priority: 0),
            new EventSubscription(EntityTransitionedEvent::class, 'onTransitioned', priority: 0),
        ];
    }

    public function onPreSave(EntityPreSaveEvent $event): void
    {
        if ($event->entityType !== 'content' || $event->bundle !== 'article') {
            return;
        }

        $title = $event->fields['title'] ?? null;
        if (is_string($title)) {
            $trimmedTitle = trim($title);
            $event->setField('title', $trimmedTitle);

            if (!isset($event->fields['slug']) || $event->fields['slug'] === '') {
                $event->setField('slug', self::slugify($trimmedTitle));
            }
        }
    }

    public function onPostSave(EntityPostSaveEvent $event): void
    {
        if ($event->record->entityType !== 'content' || $event->record->bundle !== 'article') {
            return;
        }

        // Safe post-commit side effect: record has already been persisted atomically.
        $this->searchIndex->recordUpsert(
            entityId: $event->record->id,
            revisionId: $event->record->revisionId,
            isNew: $event->isNew,
            state: $event->record->state,
        );
    }

    public function onTransitioned(EntityTransitionedEvent $event): void
    {
        if ($event->record->entityType !== 'content' || $event->record->bundle !== 'article') {
            return;
        }

        if ($event->toState === WorkflowState::Published && $event->fromState !== WorkflowState::Published) {
            $this->searchIndex->recordPublished(
                entityId: $event->record->id,
                actorId: $event->actorId,
            );
        }
    }

    private static function slugify(string $text): string
    {
        $slug = strtolower(trim($text));
        $slug = preg_replace('/[^a-z0-9]+/', '-', $slug) ?? '';

        return trim($slug, '-') !== '' ? trim($slug, '-') : 'untitled';
    }
}
```

And a simple collaborator (`src/Event/SearchIndexBuffer.php`) that you can back with a real queue or HTTP client in production and inspect directly in tests:

```php
<?php

declare(strict_types=1);

namespace Acme\Editorial\Event;

use PhrameCms\Entity\Workflow\WorkflowState;

final class SearchIndexBuffer
{
    /** @var list<array{event: string, entityId: string, state?: string, actorId?: string}> */
    public array $events = [];

    public function recordUpsert(string $entityId, string $revisionId, bool $isNew, WorkflowState $state): void
    {
        $this->events[] = [
            'event' => $isNew ? 'created' : 'updated',
            'entityId' => $entityId,
            'state' => $state->value,
        ];
    }

    public function recordPublished(string $entityId, string $actorId): void
    {
        $this->events[] = [
            'event' => 'published',
            'entityId' => $entityId,
            'actorId' => $actorId,
        ];
    }
}
```

---

## Step 2: Register the Subscriber in Your Module

Tag the subscriber with `EventSubscriberInterface::SERVICE_TAG` (`phrame.event_subscriber`). `Kernel::boot()` discovers all tagged subscribers and registers their `EventSubscription` methods with `ListenerProvider` automatically:

```php
<?php

declare(strict_types=1);

namespace Acme\Editorial;

use Acme\Editorial\Event\ArticleLifecycleSubscriber;
use Acme\Editorial\Event\SearchIndexBuffer;
use PhrameCms\Core\Contract\ContainerBuilderInterface;
use PhrameCms\Core\Contract\EventSubscriberInterface;
use PhrameCms\Core\Contract\ModuleInterface;
use PhrameCms\Entity\EntityModule;
use Psr\Container\ContainerInterface;

final readonly class EditorialModule implements ModuleInterface
{
    public const string NAME = 'acme.editorial';

    public function name(): string
    {
        return self::NAME;
    }

    /** @return list<string> */
    public function dependencies(): array
    {
        return [EntityModule::NAME];
    }

    public function register(ContainerBuilderInterface $builder): void
    {
        $builder->autowire(SearchIndexBuffer::class);
        $builder->autowire(ArticleLifecycleSubscriber::class, [EventSubscriberInterface::SERVICE_TAG]);
    }

    public function boot(ContainerInterface $container): void {}
}
```

---

## Step 3: Verify Lifecycle Events & Dry-Run Isolation In-Process

```php
<?php

declare(strict_types=1);

namespace Acme\Editorial\Tests;

use Acme\Editorial\EditorialModule;
use Acme\Editorial\Event\SearchIndexBuffer;
use PhrameCms\Config\ConfigModule;
use PhrameCms\Core\Kernel;
use PhrameCms\Core\Operation\ExecutionContext;
use PhrameCms\Core\Operation\OperationBus;
use PhrameCms\Core\Operation\OperationRequest;
use PhrameCms\Core\Security\ActorType;
use PhrameCms\Database\DatabaseModule;
use PhrameCms\Database\Schema\SchemaInstallRunner;
use PhrameCms\Entity\EntityModule;
use PhrameCms\User\Security\AuthenticatedActor;
use PhrameCms\User\UserModule;
use PHPUnit\Framework\TestCase;

final class ArticleLifecycleSubscriberTest extends TestCase
{
    public function testPopulatesSlugAndFiresOnlyOnLiveCommits(): void
    {
        $kernel = new Kernel([
            new DatabaseModule('memory://'),
            new ConfigModule(),
            new UserModule(),
            new EntityModule(),
            new EditorialModule(),
        ]);
        $kernel->boot();

        $container = $kernel->container();
        $container->getTyped(SchemaInstallRunner::class, SchemaInstallRunner::class)->installAll();

        $bus = $container->getTyped(OperationBus::class, OperationBus::class);
        $buffer = $container->getTyped(SearchIndexBuffer::class, SearchIndexBuffer::class);
        $actor = new AuthenticatedActor(id: 'usr_editor', type: ActorType::Human, scopes: ['*']);
        $liveCtx = new ExecutionContext($actor, 'evt-live');

        // Define content/article schema
        $bus->execute(new OperationRequest('entity_type.create', ['id' => 'content', 'label' => 'Content'], $liveCtx));
        $bus->execute(new OperationRequest('bundle.create', ['entity_type' => 'content', 'id' => 'article', 'label' => 'Article'], $liveCtx));
        $bus->execute(new OperationRequest('field_storage.create', ['entity_type' => 'content', 'name' => 'title', 'type' => 'string'], $liveCtx));
        $bus->execute(new OperationRequest('field_storage.create', ['entity_type' => 'content', 'name' => 'slug', 'type' => 'slug'], $liveCtx));
        $bus->execute(new OperationRequest('field_instance.attach', [
            'entity_type' => 'content', 'bundle' => 'article', 'field_name' => 'title', 'label' => 'Title', 'required' => true,
        ], $liveCtx));
        $bus->execute(new OperationRequest('field_instance.attach', [
            'entity_type' => 'content', 'bundle' => 'article', 'field_name' => 'slug', 'label' => 'Slug', 'required' => false,
        ], $liveCtx));

        // 1. Dry-run create MUST NOT fire post-save side effects
        $bus->execute(new OperationRequest(
            operation: 'entity.create',
            input: ['entity_type' => 'content', 'bundle' => 'article', 'fields' => ['title' => 'Dry Run Only']],
            context: new ExecutionContext($actor, 'evt-dry', dryRun: true),
        ));
        self::assertSame([], $buffer->events);

        // 2. Live create runs EntityPreSaveEvent (auto-slug) and EntityPostSaveEvent
        $created = $bus->execute(new OperationRequest(
            operation: 'entity.create',
            input: ['entity_type' => 'content', 'bundle' => 'article', 'fields' => ['title' => '  Hello PhrameCMS!  ']],
            context: $liveCtx,
        ));
        $entityId = (string) $created->data['entity']['id'];

        self::assertSame('Hello PhrameCMS!', $created->data['entity']['fields']['title']);
        self::assertSame('hello-phramecms', $created->data['entity']['fields']['slug']);
        self::assertCount(1, $buffer->events);
        self::assertSame('created', $buffer->events[0]['event']);

        // 3. Workflow transition to published fires EntityTransitionedEvent post-commit
        $bus->execute(new OperationRequest(
            operation: 'entity.transition',
            input: ['id' => $entityId, 'state' => 'published', 'log_message' => 'Ship it'],
            context: $liveCtx,
        ));

        self::assertCount(2, $buffer->events);
        self::assertSame('published', $buffer->events[1]['event']);
        self::assertSame('usr_editor', $buffer->events[1]['actorId']);
    }
}
```

## Related Documentation

- [Custom Modules Guide](../guides/custom-modules.md) — Complete table of all built-in domain and alter events.
- [Service Tags Reference](../reference/service-tags.md) — Priority and registration semantics for `phrame.event_subscriber`.
