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

Messenger Laravel Package

sulu/messenger

Symfony Messenger add-on for Sulu providing stamps and middlewares to configure the Sulu message bus. Includes UnpackExceptionMiddleware to surface real handler errors and LockMiddleware to prevent concurrent access. Usable standalone in any Symfony app.

View on GitHub
Deep Wiki
Context7

Product Decisions This Supports

  • Decoupling Business Logic from Immediate Execution: Adopt a message-driven architecture (MDA) to replace direct API calls or cron jobs with async message handlers. Ideal for Laravel applications with:

    • Background jobs (e.g., sending emails, generating reports, processing payments).
    • Event-driven workflows (e.g., order fulfillment, notifications).
    • Long-running tasks (e.g., video encoding, third-party API calls). Example: Replace a slow User::updateProfile() API endpoint with a ProfileUpdatedMessage handled asynchronously.
  • Concurrency and Race Condition Prevention: Implement distributed locking via LockMiddleware to protect critical resources in high-traffic Laravel apps, such as:

    • Inventory systems (prevent overselling).
    • Reservation systems (e.g., hotel bookings, event tickets).
    • Financial transactions (e.g., payment processing). Example: Lock a Product entity during stock updates to avoid race conditions when multiple users request the same item.
  • Database Consistency Without Global Transactions: Use DoctrineFlushMiddleware to opt-in flush operations for Doctrine entities, avoiding:

    • Performance overhead of global transactions.
    • N+1 query issues in Laravel’s Eloquent (if using Doctrine via a bridge). Example: Flush only after a UserOrder is fully processed, ensuring related OrderItem entities are saved without forcing a full transaction.
  • Improved Error Handling and Observability: Leverage UnpackExceptionMiddleware to surface raw exceptions from failed handlers, enabling:

    • Custom HTTP error responses (e.g., map HandlerFailedException to 422 Unprocessable Entity in Laravel APIs).
    • Better logging and monitoring (e.g., track failed message handlers in Sentry or Laravel Horizon). Example: Catch a PaymentFailedException in a handler and return a user-friendly error message via a Laravel controller.
  • Roadmap for Scalable Architecture:

    • Event Sourcing: Use messages to capture state changes (e.g., OrderCreatedEvent, PaymentProcessedEvent) for auditability.
    • Saga Patterns: Orchestrate complex workflows (e.g., multi-step approvals) with compensating transactions.
    • Idempotency: Extend the package to add idempotency keys for retries (e.g., via custom middleware).
    • Microservices: Decouple services by having them communicate via messages (e.g., UserService publishes UserUpdatedMessage for NotificationService to consume).
  • Build vs. Buy:

    • Buy: Avoid reinventing middleware for locking, flushing, or exception handling. The package is Symfony-native and integrates with Laravel via spatie/laravel-messenger or direct Symfony components.
    • Extend: Customize or add middleware (e.g., logging, metrics, or Laravel-specific features like queue retries).
    • Avoid: Rolling your own message bus if you need Symfony compatibility, Doctrine integration, or locking mechanisms in Laravel.

When to Consider This Package

Adopt When:

  • Your Laravel app uses Symfony Messenger (via spatie/laravel-messenger or direct symfony/messenger integration) and PHP 8.2+ (Laravel 10+).
  • You need distributed locking for race-condition-prone workflows (e.g., e-commerce, reservations, financial systems).
  • You require fine-grained Doctrine flush control (e.g., avoiding global transactions or N+1 queries in Doctrine-based Laravel apps).
  • You’re building an event-driven or CQRS architecture and want to standardize message handling across your codebase.
  • You prioritize observability and need to surface handler exceptions cleanly (e.g., for Laravel API error responses).
  • Your team is using Doctrine ORM alongside Laravel (e.g., for complex queries or legacy systems) and wants to leverage DoctrineFlushMiddleware.
  • You’re planning to scale background jobs and need middleware for retries, idempotency, or concurrency control.

Look Elsewhere When:

  • You’re not using Symfony Messenger in Laravel: The package is tightly coupled to Symfony’s Messenger component. Consider:
    • Laravel’s native queue system (Illuminate\Queue) for simple background jobs.
    • league/amqp or php-amqplib for advanced AMQP-based messaging.
  • You need built-in idempotency: While the package supports middleware, idempotency isn’t natively included. Consider:
    • Laravel’s Illuminate\Queue\InteractsWithQueue with custom retry logic.
    • symfony/messenger-bundle (if using Symfony) or spatie/laravel-queue-scheduler.
  • You require advanced retry logic: The package doesn’t include retry middleware. Evaluate:
    • Laravel’s failed() method for job retries.
    • symfony/messenger-bundle’s retry features.
  • Your use case is low-concurrency: Overhead of locking/flushing may not justify the complexity for simple Laravel apps.
  • You’re not using Doctrine ORM: DoctrineFlushMiddleware won’t work with Laravel’s Eloquent. Use Eloquent’s built-in flush or transactions instead.
  • You need multi-language support: The package is PHP-only. For polyglot messaging, consider:
    • Event bridges (e.g., Laravel events + Symfony Messenger).
    • gRPC or Kafka for cross-language communication.

How to Pitch It (Stakeholders)

For Executives:

"This package helps us build scalable, resilient Laravel applications by adopting a message-driven architecture. Here’s why it’s worth investing in:

  • Faster, More Reliable APIs: Offload slow or blocking operations (e.g., PDF generation, third-party calls) to background jobs, improving response times and user experience.
  • Prevent Costly Errors: Built-in locking ensures no race conditions in high-traffic systems (e.g., e-commerce inventory, reservations), reducing chargebacks or data corruption.
  • Cleaner Codebase: Standardized message handling makes the system easier to debug, extend, and maintain—critical as we scale.
  • Future-Proof: Supports complex workflows like event sourcing, sagas, and microservices, aligning with our long-term architecture goals.

It’s a low-risk choice: MIT-licensed, tested in production by Sulu CMS, and integrates seamlessly with our existing Laravel/Symfony stack. We can start with simple use cases (e.g., async notifications) and expand to critical systems later."


For Engineering (Laravel Team):

"This is a Symfony Messenger extension that adds three powerful middlewares to Laravel’s queue/job system:

  1. LockMiddleware: Solves race conditions with granular locking (e.g., LockStamp('product-123')). Supports TTL and auto-release—ideal for inventory or payment systems.
  2. DoctrineFlushMiddleware: Opt-in flushing via EnableFlushStamp (requires Doctrine ORM). Avoids global transactions or N+1 queries.
  3. UnpackExceptionMiddleware: Exposes raw handler exceptions for better error handling (e.g., map to HTTP 422 in Laravel APIs).

Why use it?

  • No reinvention: Avoid writing custom middleware for locking/flushing.
  • Symfony-native: Works with spatie/laravel-messenger or direct Symfony components.
  • Laravel-compatible: Integrates with queues, jobs, and Doctrine (if used).

Proposal: Start by replacing a high-failure-rate API endpoint with a message handler + queue. For example:

  • Before: A slow User::updateProfile() endpoint blocks requests.
  • After: Dispatch a ProfileUpdatedMessage to a queue, with locking to prevent concurrent updates.

Next steps:

  1. Set up spatie/laravel-messenger (if not already using Symfony Messenger).
  2. Add the package via Composer: composer require sulu/messenger.
  3. Test with a non-critical workflow (e.g., sending welcome emails).
  4. Measure performance/throughput gains.

Potential challenges:

  • Doctrine ORM dependency (not needed for Eloquent-only apps).
  • Requires Symfony Messenger (but spatie/laravel-messenger bridges the gap)."*

For Data/DevOps Teams:

"This package improves system reliability and observability by:

  • Preventing data corruption: Locking ensures no race conditions in shared resources (e.g., database rows, external APIs).
  • Better error tracking: Raw exceptions from failed handlers can be logged or mapped to HTTP errors (e.g., 422 for invalid messages).
  • Database consistency: Opt-in flushing reduces transaction overhead and N+1 queries in Doctrine-based workflows.

Impact:

  • Fewer production incidents related to race conditions or inconsistent data.
  • Easier debugging with clear exception surfacing.
  • More efficient database usage with targeted flushes.

Recommendation: Pilot in a high-risk area (e.g., payment processing) to validate locking/flushing benefits."*

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.
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony
spatie/flare-daemon-runtime
canaltp/sam-ecore-application-manager-bundle
canaltp/sam-ecore-security-manager-bundle