PHP code example of solidframe / event-driven

1. Go to this page and download the library: Download solidframe/event-driven 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/ */

    

solidframe / event-driven example snippets


use SolidFrame\Core\Event\DomainEventInterface;

final readonly class OrderPlaced implements DomainEventInterface
{
    public function __construct(
        public string $orderId,
        public string $customerId,
        private DateTimeImmutable $occurredAt = new DateTimeImmutable(),
    ) {}

    public function eventName(): string
    {
        return 'order.placed';
    }

    public function occurredAt(): DateTimeImmutable
    {
        return $this->occurredAt;
    }
}

use SolidFrame\EventDriven\EventListener;

final readonly class SendOrderConfirmation implements EventListener
{
    public function __construct(private Mailer $mailer) {}

    public function __invoke(OrderPlaced $event): void
    {
        $this->mailer->send($event->customerId, 'Your order has been placed.');
    }
}

final readonly class UpdateInventory implements EventListener
{
    public function __construct(private InventoryService $inventory) {}

    public function __invoke(OrderPlaced $event): void
    {
        $this->inventory->reserve($event->orderId);
    }
}

$eventBus->dispatch(new OrderPlaced(
    orderId: 'order-123',
    customerId: 'customer-456',
));
// Both SendOrderConfirmation and UpdateInventory will be called

use SolidFrame\EventDriven\Listener\InMemoryListenerResolver;
use SolidFrame\EventDriven\Bus\EventBus;

$resolver = new InMemoryListenerResolver();
$resolver->listen(OrderPlaced::class, new SendOrderConfirmation($mailer));
$resolver->listen(OrderPlaced::class, new UpdateInventory($inventory));

$eventBus = new EventBus($resolver);
$eventBus->dispatch(new OrderPlaced('order-123', 'customer-456'));

use SolidFrame\Core\Middleware\MiddlewareInterface;

final readonly class EventLoggingMiddleware implements MiddlewareInterface
{
    public function __construct(private LoggerInterface $logger) {}

    public function handle(object $message, callable $next): mixed
    {
        $this->logger->info('Event dispatched', [
            'event' => $message::class,
        ]);

        return $next($message);
    }
}

$eventBus = new EventBus($resolver, [
    new EventLoggingMiddleware($logger),
]);