dekalee/pubsub-swarrot
Laravel package integrating Swarrot for Pub/Sub messaging, providing an easy way to publish and consume messages through configurable transports and processors. Useful for async jobs, event-driven apps, and message queue workflows.
Installation:
composer require dekalee/pubsub-swarrot
Add the service provider to config/app.php:
Dekalee\PubSubSwarrot\PubSubSwarrotServiceProvider::class,
Basic Configuration: Publish the config file:
php artisan vendor:publish --provider="Dekalee\PubSubSwarrot\PubSubSwarrotServiceProvider" --tag="config"
Edit config/pubsub-swarrot.php to define your Pub/Sub topics and subscriptions.
First Use Case: Publish a message to a topic:
use Dekalee\PubSubSwarrot\Facades\PubSub;
PubSub::publish('user.created', ['user_id' => 123]);
Subscribe to a topic in a controller or service:
PubSub::subscribe('user.created', function ($message) {
// Handle the message
Log::info('User created:', $message);
});
Event-Driven Architecture: Use Pub/Sub for decoupling services. Example:
// In UserController
public function store(Request $request) {
$user = User::create($request->all());
PubSub::publish('user.created', $user->toArray());
}
// In NotificationService
PubSub::subscribe('user.created', function ($user) {
Notification::send($user, 'welcome');
});
Background Jobs: Offload processing to queues by subscribing to topics:
PubSub::subscribe('order.processed', function ($order) {
dispatch(new ProcessOrderJob($order));
});
Real-Time Updates: Combine with Laravel Echo/Pusher for live updates:
PubSub::subscribe('chat.message', function ($message) {
broadcast(new ChatMessageBroadcast($message))->toOthers();
});
Middleware: Use middleware to validate or transform messages before publishing:
PubSub::extend('user.created', function ($broker) {
return new class($broker) {
public function publish($message) {
if (!isset($message['user_id'])) {
throw new \InvalidArgumentException('Missing user_id');
}
$this->broker->publish($message);
}
};
});
Testing: Mock subscriptions in tests:
$mock = Mockery::mock();
PubSub::subscribe('test.topic', $mock);
PubSub::publish('test.topic', ['data' => 'test']);
$mock->shouldHaveReceived('__invoke');
Memory Leaks: Ensure subscriptions are unsubscribed when no longer needed (e.g., in route closures or short-lived services). Use:
$subscription = PubSub::subscribe('topic', $callback);
// Later...
$subscription->unsubscribe();
Race Conditions: Pub/Sub is asynchronous. Avoid relying on immediate side effects in subscribers. Use queues or retries for critical operations.
Config Overrides: Default config may not match your environment. Always verify:
config('pubsub-swarrot.default_topic');
PubSub::subscribe('*.*', function ($message, $topic) {
Log::debug("Topic: {$topic}, Message: " . json_encode($message));
});
Custom Brokers:
Extend the Broker interface to support non-default transports (e.g., Redis, Kafka):
PubSub::extend('kafka', function () {
return new KafkaBroker();
});
Message Serialization: Override serialization for complex objects:
PubSub::extend('user.created', function ($broker) {
return new class($broker) {
public function publish($user) {
$this->broker->publish('user.created', [
'data' => $user->serializeForPubSub(),
]);
}
};
});
Wildcard Topics:
Use wildcards (*.*) for global subscribers, but be mindful of performance:
PubSub::subscribe('*.created', function ($message, $topic) {
// Handle all "created" events
});
How can I help you explore Laravel packages today?