Messaging
Introduction
Sukarix\Messaging\CommandPublisher is a small interface for publishing JSON commands onto a message bus — telling
another service to do something, as opposed to the request/response of a web action or the work-queue polling of
Queues:
interface CommandPublisher
{
public function publish(string $routingKey, array $payload): void;
}
Two implementations ship with the framework:
Sukarix\Messaging\AmqpPublisher— publishes onto a direct-exchange RabbitMQ bus.Sukarix\Messaging\RecordingPublisher— records published messages in memory instead of sending them, for tests.
Publishing to RabbitMQ
use Sukarix\Messaging\AmqpPublisher;
$publisher = new AmqpPublisher($dsn, $exchange);
$publisher->publish('user.created', ['id' => $user->id]);
Both constructor arguments are plain values — a DSN (amqp://user:pass@host:port) and an exchange name — so wiring
one up through the Injector under your own alias is a one-line
factory. AmqpPublisher opens a connection, declares the exchange, publishes, and closes the connection on every
call; it does not hold a connection open between calls, so it suits code that publishes occasionally rather than a
high-throughput producer.
Testing Code That Publishes
Depend on CommandPublisher, not AmqpPublisher, in the code under test, and swap in RecordingPublisher to assert
on what was sent without a broker:
use Sukarix\Messaging\RecordingPublisher;
$publisher = new RecordingPublisher();
$service = new OrderService($publisher);
$service->confirm($order);
$test->expect('order.confirmed' === $publisher->messages[0]['routing_key'], 'the confirmation event was published');
$messages is a plain array of ['routing_key' => ..., 'payload' => ...] entries, in publish order.