PHP code example of rekalogika / domain-event

1. Go to this page and download the library: Download rekalogika/domain-event 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 example snippets


//
// The event
//

final readonly class PostPublished
{
    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 setStatus(string $status): void
    {
        $originalStatus = $this->status;
        $this->status = $status;

        // records the published event if the new status is published and it
        // is different from the original status

        if ($status === 'published' && $originalStatus !== $status) {
            $this->recordEvent(new PostPublished($this->id));
        }
    }

    // ...
}

//
// The listener
//

use Psr\Log\LoggerInterface;
use Rekalogika\Contracts\DomainEvent\Attribute\AsPostFlushDomainEventListener;

class PostEventListener
{
    public function __construct(private LoggerInterface $logger) {}

    // will be called after the post is published and the entity manager is
    // flushed
    
    #[AsPostFlushDomainEventListener]
    public function onPostPublished(PostPublished $event) {
        $postId = $event->postId;

        $this->logger->info("Post $postId has been published.");
    }
}

//
// The caller
//

use Doctrine\ORM\EntityManagerInterface;

/** @var Post $post */
/** @var EntityManagerInterface $entityManager */

$post->setStatus('published');
$entityManager->flush();

// the event will be dispatched after the flush above, afterwards the listener
// above will be called, sending a message to the logger