PHP code example of ahmedosamir732 / eventbus-php

1. Go to this page and download the library: Download ahmedosamir732/eventbus-php 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/ */

    

ahmedosamir732 / eventbus-php example snippets


use Idaratech\EventBus\Contracts\ContextProviderInterface;

class AppContextProvider implements ContextProviderInterface
{
    public function getTenantId(): int|string|null { /* ... */ }
    public function getWorkspace(): string { /* ... */ }
    public function getActor(): array { /* ... */ }
    public function getCorrelationId(): ?string { /* ... */ }
}

'context_provider' => App\EventBus\AppContextProvider::class,

use Idaratech\EventBus\Contracts\EventBusInterface;
use Idaratech\EventBus\IntegrationEventFactory;

class SomeService
{
    public function __construct(
        private EventBusInterface $bus,
        private IntegrationEventFactory $factory,
    ) {}

    public function doWork(): void
    {
        $event = $this->factory->create(
            eventType: 'user.created',
            version: '1.0',
            payload: ['user_id' => 123, 'email' => '[email protected]'],
        );

        $this->bus->publish('my-exchange', $event);
    }
}

use Idaratech\EventBus\Contracts\EventHandlerInterface;
use Idaratech\EventBus\Contracts\IntegrationEventInterface;

class UserCreatedHandler implements EventHandlerInterface
{
    public function supports(string $eventType): bool
    {
        return $eventType === 'user.created';
    }

    public function handle(IntegrationEventInterface $event): void
    {
        $payload = $event->getPayload();
        // Process the event...
    }
}

$this->app->tag([UserCreatedHandler::class], 'eventbus.handlers');

'consumers' => [
    [
        'queue' => 'my-events',
        'retryExchange' => 'my-events.retry',
        'dlqRoutingKey' => 'my-events.dlq',
        'maxRetries' => 3,
        'retryDelays' => [1000, 5000, 25000],
        'prefetchCount' => 1,
    ],
],

'hooks' => [
    'before_handle' => function (IntegrationEventInterface $event) {
        // Initialize tenant context, set log context, etc.
    },
    'after_handle' => function (?IntegrationEventInterface $event) {
        // Clean up tenant context, flush logs, etc.
    },
],
bash
composer 
bash
php artisan vendor:publish --tag=eventbus-config
bash
php artisan eventbus:consume --memory-limit=128 --timeout=0
bash
php artisan eventbus:replay-dlq