PHP code example of rabbitevents / symfony-bundle

1. Go to this page and download the library: Download rabbitevents/symfony-bundle 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/ */

    

rabbitevents / symfony-bundle example snippets


return [
    // ...
    RabbitEvents\Bundle\RabbitEventsBundle::class => ['all' => true],
];

namespace App\Event;

use RabbitEvents\Bundle\Publisher\AbstractPublishableEvent;

class OrderCreatedEvent extends AbstractPublishableEvent
{
    public function __construct(public readonly int $orderId)
    {
    }

    public function publishEventKey(): string
    {
        return 'order.created';
    }

    public function toPublish(): array
    {
        return [
            'order_id' => $this->orderId,
            'timestamp' => time(),
        ];
    }
}

// Publish from anywhere:
(new OrderCreatedEvent(12345))->publish();

namespace App\Listener;

use RabbitEvents\Bundle\Listener\Attribute\AsRabbitListener;

#[AsRabbitListener(event: 'order.created')]
class OrderCreatedListener
{
    public function handle(array $payload): void
    {
        // Handle payload: ['order_id' => 12345, 'timestamp' => ...]
        echo sprintf("Order #%d created!\n", $payload['order_id']);
    }
}

namespace App\Event;

use RabbitEvents\Bundle\Publisher\AbstractPublishableEvent;

class UserRegisteredEvent extends AbstractPublishableEvent
{
    public function __construct(
        public readonly int $userId,
        public readonly string $email
    ) {
    }

    public function publishEventKey(): string
    {
        return 'user.registered';
    }

    public function toPublish(): array
    {
        return [
            'user_id' => $this->userId,
            'email' => $this->email,
        ];
    }
}

// Publish:
$event = new UserRegisteredEvent(1, '[email protected]');
$event->publish();

namespace App\Service;

use App\Event\UserRegisteredEvent;
use RabbitEvents\Bundle\Publisher;

class UserService
{
    public function __construct(
        private readonly Publisher $publisher
    ) {
    }

    public function register(string $email): void
    {
        // ... save user ...
        $this->publisher->publish(new UserRegisteredEvent($user->getId(), $email));
    }
}

namespace App\Event;

use RabbitEvents\Bundle\Publisher\ShouldPublish;

class InvoiceGeneratedEvent implements ShouldPublish
{
    public function __construct(public readonly string $invoiceNumber) {}

    public function publishEventKey(): string
    {
        return 'invoice.generated';
    }

    public function toPublish(): array
    {
        return ['invoice_number' => $this->invoiceNumber];
    }
}

namespace App\Listener;

use Psr\Log\LoggerInterface;
use RabbitEvents\Bundle\Listener\Attribute\AsRabbitListener;

#[AsRabbitListener(event: 'order.created')]
class OrderCreatedListener
{
    public function __construct(
        private readonly LoggerInterface $logger
    ) {
    }

    public function handle(array $payload): void
    {
        $this->logger->info('Order received', ['order_id' => $payload['order_id']]);
    }
}

namespace App\Listener;

use Psr\Log\LoggerInterface;
use RabbitEvents\Bundle\Listener\Attribute\AsRabbitListener;

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

    #[AsRabbitListener(event: 'order.created')]
    public function onCreated(array $payload): void
    {
        $this->logger->info('Order created', $payload);
    }

    #[AsRabbitListener(event: 'order.updated')]
    public function onUpdated(array $payload): void
    {
        $this->logger->info('Order updated', $payload);
    }

    #[AsRabbitListener(event: 'order.cancelled')]
    public function onCancelled(array $payload): void
    {
        $this->logger->warning('Order cancelled', $payload);
    }
}

#[AsRabbitListener(event: 'order.*')]
class AllOrderEventsListener
{
    public function handle(array $payload): void
    {
        // Receives all order.* events
    }
}

#[AsRabbitListener(event: 'payment.processed')]
class PaymentListener
{
    public function handle(array $payload): void
    {
        // May throw an exception if payment gateway is down
    }

    public function failed(\Throwable $exception): void
    {
        // Cleanup, send alerts to Slack / Sentry, etc.
    }
}

namespace App\Tests;

use App\Event\OrderCreatedEvent;
use App\Service\OrderService;
use PHPUnit\Framework\TestCase;
use RabbitEvents\Bundle\Publisher\PublishableEventTesting;

class OrderServiceTest extends TestCase
{
    use PublishableEventTesting;

    protected function setUp(): void
    {
        parent::setUp();
        self::fake(); // Replaces the real Publisher with a testing spy
    }

    public function testOrderCreatesEvent(): void
    {
        $service = new OrderService();
        $service->createOrder(orderId: 100);

        OrderCreatedEvent::assertPublished('order.created', [
            'order_id' => 100,
        ]);
    }

    public function testEventNotPublishedOnFailure(): void
    {
        $service = new OrderService();
        // ... action that should not publish ...

        OrderCreatedEvent::assertNotPublished();
    }
}