Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Pubsub Swarrot Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require dekalee/pubsub-swarrot
    

    Add the service provider to config/app.php:

    Dekalee\PubSubSwarrot\PubSubSwarrotServiceProvider::class,
    
  2. 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.

  3. 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);
    });
    

Implementation Patterns

Workflows

  1. 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');
    });
    
  2. Background Jobs: Offload processing to queues by subscribing to topics:

    PubSub::subscribe('order.processed', function ($order) {
        dispatch(new ProcessOrderJob($order));
    });
    
  3. Real-Time Updates: Combine with Laravel Echo/Pusher for live updates:

    PubSub::subscribe('chat.message', function ($message) {
        broadcast(new ChatMessageBroadcast($message))->toOthers();
    });
    

Integration Tips

  • 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');
    

Gotchas and Tips

Pitfalls

  1. 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();
    
  2. Race Conditions: Pub/Sub is asynchronous. Avoid relying on immediate side effects in subscribers. Use queues or retries for critical operations.

  3. Config Overrides: Default config may not match your environment. Always verify:

    config('pubsub-swarrot.default_topic');
    

Debugging

  • Logging: Enable debug mode in config to log all published/subscription events.
  • Message Inspection: Add a subscriber for debugging:
    PubSub::subscribe('*.*', function ($message, $topic) {
        Log::debug("Topic: {$topic}, Message: " . json_encode($message));
    });
    

Extension Points

  1. Custom Brokers: Extend the Broker interface to support non-default transports (e.g., Redis, Kafka):

    PubSub::extend('kafka', function () {
        return new KafkaBroker();
    });
    
  2. 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(),
                ]);
            }
        };
    });
    
  3. Wildcard Topics: Use wildcards (*.*) for global subscribers, but be mindful of performance:

    PubSub::subscribe('*.created', function ($message, $topic) {
        // Handle all "created" events
    });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky