PHP code example of azaharizaman / nexus-event-stream

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

    

azaharizaman / nexus-event-stream example snippets


use Nexus\EventStream\Contracts\EventStoreInterface;
use Nexus\Finance\Events\AccountCreditedEvent;

// In Nexus\Finance\Services\LedgerManager
public function __construct(
    private readonly EventStoreInterface $eventStore
) {}

public function postJournalEntry(JournalEntry $entry): void
{
    foreach ($entry->getLines() as $line) {
        if ($line->isCredit()) {
            $this->eventStore->append(
                $line->getAccountId(),
                new AccountCreditedEvent(
                    accountId: $line->getAccountId(),
                    amount: $line->getAmount(),
                    journalEntryId: $entry->getId()
                )
            );
        }
    }
}

use Nexus\EventStream\Services\EventStreamManager;

// Get account balance at specific date
$balance = $manager->getStateAt(
    aggregateId: 'account-1000',
    timestamp: new \DateTimeImmutable('2024-10-15')
);

use Nexus\EventStream\Contracts\ProjectorInterface;

// Projection rebuilds current balance from events
class CurrentBalanceProjector implements ProjectorInterface
{
    public function project(EventInterface $event): void
    {
        if ($event instanceof AccountCreditedEvent) {
            $this->balances[$event->accountId] += $event->amount;
        }
    }
}