PHP code example of rekalogika / domain-event-outbox
1. Go to this page and download the library: Download rekalogika/domain-event-outbox library. Choose the download type require. 2. Extract the ZIP file and open the index.php. 3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
rekalogika / domain-event-outbox example snippets
//
// The event
//
final readonly class PostChanged
{
public function __construct(public string $postId) {}
}
//
// The entity
//
use Rekalogika\Contracts\DomainEvent\DomainEventEmitterInterface;
use Rekalogika\Contracts\DomainEvent\DomainEventEmitterTrait;
class Post implements DomainEventEmitterInterface
{
use DomainEventEmitterTrait;
// ...
public function setTitle(string $title): void
{
$this->title = $title;
// highlight-next-line
$this->recordEvent(new PostChanged($this->id));
}
// ...
}
//
// The listener
//
use Psr\Log\LoggerInterface;
use Rekalogika\Contracts\DomainEvent\Attribute\AsPublishedDomainEventListener;
class PostEventListener
{
public function __construct(private LoggerInterface $logger) {}
// highlight-next-line
#[AsPublishedDomainEventListener]
public function onPostChanged(PostChanged $event) {
$postId = $event->postId;
$this->logger->info("Post $postId has been changed.");
}
}
//
// The caller
//
use Doctrine\ORM\EntityManagerInterface;
/** @var Post $post */
/** @var EntityManagerInterface $entityManager */
$post->setTitle('New title');
$entityManager->flush();
// During the flush above, the event will be recorded in the outbox table in the
// database. Then the message relay service is executed, and will publish the
// events on the event bus. When the event bus announces the event, the listener
// will be executed.