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

Doctrine Orm Bridge Laravel Package

simple-bus/doctrine-orm-bridge

Doctrine ORM bridge for SimpleBus/MessageBus. Provides command bus middleware to run command handling inside Doctrine transactions and to dispatch domain events generated by entities. Part of the SimpleBus ecosystem.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Event-Driven Architecture (EDA) Synergy: The package excels in Laravel applications leveraging CQRS, event sourcing, or domain-driven design (DDD). It bridges SimpleBus (a lightweight message bus) with Doctrine ORM, enabling atomic command execution and event-driven workflows without coupling to Laravel’s native event system.
  • Transaction Boundaries: The transaction middleware ensures commands execute within Doctrine transactions, mitigating partial updates—a critical requirement for financial, inventory, or stateful systems. This aligns with Laravel’s database layer but extends it to message-driven workflows.
  • Domain Event Decoupling: Automates the collection and dispatching of Doctrine entity events (e.g., PrePersist, PostUpdate), reducing boilerplate for side effects like notifications or analytics. This complements Laravel’s model observers but targets domain-level events rather than framework-level ones.
  • Middleware Stack Flexibility: The package integrates seamlessly with SimpleBus pipelines, allowing for cross-cutting concerns (e.g., logging, validation, retries) without polluting command handlers. This mirrors Laravel’s middleware model but applies it to messaging.

Integration Feasibility

  • Doctrine ORM Dependency: Requires Doctrine ORM (not DBAL or Eloquent). If the Laravel app uses Eloquent, a migration to Doctrine is needed, which may introduce friction (e.g., DQL vs. Query Builder, hydration strategies).
  • SimpleBus Adoption: If the team isn’t already using SimpleBus, introducing it adds complexity. However, it provides structured messaging (command/handler separation) and middleware-based retries, which Laravel’s native queue system lacks.
  • Laravel-Specific Challenges:
    • Event System Conflict: Laravel’s Illuminate\Events and this package’s domain events could overlap. Clarify whether domain events (e.g., OrderCreated) should replace or coexist with Laravel’s model events (e.g., created).
    • Service Container Integration: The bridge must be registered in Laravel’s DI container, which may require a custom service provider or adjustments to existing Doctrine configurations.
  • Transaction Management: The package handles transaction rollbacks gracefully (post-3.0.0), but Laravel’s database transactions (e.g., DB::transaction()) may conflict if not scoped properly.

Technical Risk

  • Transaction Isolation: Wrapping every command in a transaction could lead to long-running transactions or lock contention. Benchmark under load to avoid performance bottlenecks.
  • Event Deduplication: Events are erased after processing (post-2.0.1), which prevents reprocessing. This may require idempotent handlers or compensating logic for retries.
  • Failure Modes:
    • Stale Connections: If Doctrine’s EntityManager fails mid-transaction, the bridge resets it, but this could mask deeper issues (e.g., connection pools).
    • Middleware Ordering: Incorrect middleware sequencing (e.g., transaction middleware after validation) could lead to unexpected rollbacks.
  • Testing Complexity: Mocking Doctrine’s EntityManager and Connection for unit tests is non-trivial. Consider integration tests with a test database.
  • Version Lock: The package depends on SimpleBus 1.x, which may not align with newer Laravel versions or Doctrine ORM updates. Monitor for breaking changes.

Key Questions

  1. Why Not Laravel’s Native Events?
    • Does the team need command/handler separation, middleware-based retries, or asynchronous command processing beyond Laravel’s queue system?
  2. Doctrine vs. Eloquent:
    • Is the project already using Doctrine ORM, or would this require a migration? What are the trade-offs (e.g., DQL vs. Query Builder, hydration)?
  3. Transaction Scope:
    • Should all commands be transactional, or only specific ones? Can the bridge be conditionally applied via middleware?
  4. Event Handling Strategy:
    • How will domain events differ from Laravel’s model events? Will they overlap, or is this a clean separation?
  5. Error Recovery:
    • How will failed transactions be retried? Will dead-letter queues or compensating transactions be needed?
  6. Observability:
    • Are there plans to track command/event processing metrics (e.g., latency, failure rates)? The bridge lacks built-in observability.
  7. Long-Term Maintenance:
    • Is the team comfortable with MIT-licensed third-party dependencies in production-critical paths? What’s the upgrade path for SimpleBus/Doctrine?

Integration Approach

Stack Fit

  • Laravel Compatibility:
    • Doctrine ORM: Required (not DBAL or Eloquent). If using Eloquent, assess migration effort (e.g., DQL vs. Query Builder, hydration).
    • PHP 8.0+: Required by SimpleBus 1.x and Doctrine ORM 2.10+.
    • Symfony Components: The bridge relies on Symfony’s HttpFoundation and EventDispatcher, already present in Laravel’s vendor tree.
  • Alternatives:
    • Laravel Events: Suitable for simple pub/sub but lacks command bus features (e.g., middleware, retries).
    • Symfony Messenger: More feature-rich but heavier; overkill for lightweight command/event needs.
    • Custom Middleware: Possible but reinvents transaction/event handling wheels.

Migration Path

  1. Assess Current Architecture:
    • Map existing commands (e.g., API routes, jobs) to SimpleBus messages.
    • Identify domain events (e.g., OrderCreated) that should trigger side effects.
  2. Incremental Adoption:
    • Phase 1: Integrate the bridge for non-critical commands (e.g., logging, analytics).
    • Phase 2: Roll out to core workflows (e.g., order processing) with feature flags.
    • Phase 3: Replace Laravel’s event system for domain events (if applicable).
  3. Dependency Setup:
    composer require simplebus/doctrine-orm-bridge simplebus/message-bus doctrine/orm
    
  4. Service Provider Integration:
    // app/Providers/SimpleBusServiceProvider.php
    public function register()
    {
        $this->app->bind(\SimpleBus\MessageBus\MessageBus::class, function ($app) {
            $entityManager = $app->make(\Doctrine\ORM\EntityManagerInterface::class);
            $bus = new \SimpleBus\MessageBus\MessageBus(
                new \SimpleBus\MessageBus\Middleware\MiddlewareStack(
                    new \SimpleBus\DoctrineORMBridge\Middleware\TransactionMiddleware($entityManager),
                    new \SimpleBus\DoctrineORMBridge\Middleware\DomainEventMiddleware($entityManager),
                    // Add other middleware (e.g., logging, validation)
                )
            );
            return $bus;
        });
    }
    
  5. Command/Event Mapping:
    • Annotate handlers with @Command or @Event (if using SimpleBus annotations).
    • Example:
      use SimpleBus\MessageBus\Command\CommandHandler;
      
      class CreateOrderHandler implements CommandHandler
      {
          public function handle(CreateOrder $command)
          {
              $order = new Order($command->details);
              $entityManager->persist($order);
              $entityManager->flush(); // Events are collected automatically
          }
      }
      
  6. Laravel Integration Points:
    • API Routes: Dispatch commands via the message bus instead of controllers.
      Route::post('/orders', function () {
          $bus->dispatch(new CreateOrder($request->input()));
      });
      
    • Jobs/Queues: Use SimpleBus for asynchronous command processing if needed.

Compatibility

  • Doctrine ORM: Must be configured in config/database.php with a connection (e.g., MySQL, PostgreSQL).
  • SimpleBus Middleware: Can coexist with Laravel middleware but must be ordered correctly (e.g., transaction middleware before handlers).
  • Event System: Domain events from this package should not trigger Laravel’s Illuminate\Events unless explicitly bridged.

Sequencing

  1. Transaction Middleware: Wrap handlers to ensure atomicity.
  2. Domain Event Middleware: Collect and dispatch events after persistence.
  3. Validation/Logging: Add other SimpleBus middleware as needed.
  4. Laravel Middleware: Apply framework-level middleware (e.g., auth) before dispatching commands.

Operational Impact

Maintenance

  • Dependency Updates: Monitor SimpleBus, Doctrine ORM, and Symfony for breaking changes. The package is MIT-licensed but may lag behind Laravel’s ecosystem.
  • Middleware Debugging: Complex middleware stacks (e.g., transaction + validation) can be hard to debug. Use logging middleware to trace execution.
  • Doctrine Configuration: Changes to Doctrine’s EntityManager (e.g., connection pooling) may affect transaction behavior.

Support

  • Community: SimpleBus has a small but active community (29 stars, GitHub issues). Support may require self-service or contributions
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