PHP code example of complex-heart / domain-events

1. Go to this page and download the library: Download complex-heart/domain-events 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/ */

    

complex-heart / domain-events example snippets


use ComplexHeart\Domain\Contracts\Events\Event;
use ComplexHeart\Domain\Events\IsDomainEvent;

final class OrderPlaced implements Event
{
    use IsDomainEvent;

    public function __construct(
        public readonly string $orderId,
        public readonly string $customerId,
        public readonly float $total,
    ) {
    }
}

$event = OrderPlaced::new(
    orderId: 'order-123',
    customerId: 'customer-456',
    total: 99.95,
);

$event->eventId();    // "a1b2c3d4-e5f6-..." (auto-generated UUID)
$event->eventName();  // "order.placed"
$event->payload();    // ['orderId' => 'order-123', 'customerId' => 'customer-456', 'total' => 99.95]
$event->occurredOn(); // "2026-03-15T10:30:00+00:00"

// Direct property access also works
$event->orderId;      // "order-123"

use ComplexHeart\Domain\Contracts\Model\Aggregate;
use ComplexHeart\Domain\Model\IsAggregate;

class Order extends Model implements Aggregate
{
    use IsAggregate;

    public static function place(string $id, string $customerId, float $total): static
    {
        $order = static::new(id: $id, customerId: $customerId, total: $total);
        $order->registerDomainEvent(
            OrderPlaced::new(orderId: $id, customerId: $customerId, total: $total)
        );
        return $order;
    }
}

final readonly class PlaceOrder
{
    public function __construct(
        private OrderRepository $orders,
        private EventBus $eventBus,
    ) {
    }

    public function __invoke(string $id, string $customerId, float $total): Order
    {
        $order = Order::place($id, $customerId, $total);
        $this->orders->store($order);
        $order->publishDomainEvents($this->eventBus);
        return $order;
    }
}