PHP code example of xerxes / laravel-rabbitmq-communication

1. Go to this page and download the library: Download xerxes/laravel-rabbitmq-communication 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/ */

    

xerxes / laravel-rabbitmq-communication example snippets


use Xerxes\RabbitMQ\RabbitMQ;

app(RabbitMQ::class)
    ->message()
    ->viaExchange('my.exchange')
    ->route('my.routing.key')
    ->withPayload(['event' => 'user.created', 'data' => [...]])
    ->persistent()
    ->publish();

app(RabbitMQ::class)
    ->message()
    ->viaExchange('my.exchange')
    ->route('my.routing.key')
    ->withPayload($payload)
    ->withHeaders(['x-custom-header' => 'value'])
    ->persistent()
    ->publish();

app(RabbitMQ::class)
    ->message()
    ->viaExchange('my.exchange')
    ->route('my.routing.key')
    ->withPayload($payload)
    ->publish();

use Xerxes\RabbitMQ\Support\ShouldPublish;

class UserCreated implements ShouldPublish
{
    public string $exchange = 'user.events';

    public function __construct(
        public User $user
    ) {}

    public function routingKey(): string
    {
        return 'user.created';
    }
}

// Dispatch normally - automatically published to RabbitMQ
event(new UserCreated($user));

'event-consumers' => [
    [
        'exchange' => 'user.events',
        'exchange_type' => 'topic',
        'routing_key' => 'user.#',
        'handler' => [\App\Handlers\UserHandler::class, 'handle'],
        'queue' => 'my-app.users',
    ],
],

use Xerxes\RabbitMQ\Contracts\MessageHandler;

class UserHandler implements MessageHandler
{
    public function handle(array $payload, ?string $routingKey = null): void
    {
        // Process the message
        Log::info('Processing user event', [
            'routing_key' => $routingKey,
            'payload' => $payload,
        ]);
    }
}
bash
php artisan vendor:publish --tag=laravel-rabbitmq-communication-config
bash
php artisan migrate
bash
php artisan outbox:work
bash
php artisan rabbitmq:consume-events