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

Cqrs Bundle Laravel Package

ano/cqrs-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require ano/cqrs-bundle
    

    Register the bundle in config/bundles.php:

    return [
        // ...
        Ano\CqrsBundle\AnoCqrsBundle::class => ['all' => true],
    ];
    
  2. First Use Case: Command Handling Define a command class (e.g., CreateUserCommand):

    namespace App\Command;
    
    use Ano\CqrsBundle\Command\Command;
    
    class CreateUserCommand implements Command
    {
        public $name;
        public $email;
    }
    

    Create a handler (e.g., CreateUserCommandHandler):

    namespace App\Command\Handler;
    
    use App\Command\CreateUserCommand;
    use Ano\CqrsBundle\Command\CommandHandler;
    
    class CreateUserCommandHandler implements CommandHandler
    {
        public function handle(CreateUserCommand $command)
        {
            // Business logic here
            return new UserCreatedEvent($command->email);
        }
    }
    
  3. Dispatching Commands Inject the CommandBus into your controller/service:

    use Ano\CqrsBundle\Command\CommandBus;
    
    class UserController
    {
        public function __construct(private CommandBus $commandBus) {}
    
        public function createUser()
        {
            $command = new CreateUserCommand();
            $command->name = 'John Doe';
            $command->email = 'john@example.com';
    
            $this->commandBus->dispatch($command);
        }
    }
    

Implementation Patterns

Command-Query Separation

  • Commands are used for state-changing operations (e.g., CreateUserCommand, UpdateUserCommand).
  • Queries (if supported) are used for read operations (e.g., GetUserQuery). Note: The bundle relies on beberlei/lite-cqrs, which primarily focuses on commands.

Event Sourcing (Optional)

Leverage events for auditing or side effects:

// In handler:
return new UserCreatedEvent($command->email);

// Subscribe to events:
use Ano\CqrsBundle\Event\EventSubscriber;

class UserCreatedEventSubscriber implements EventSubscriber
{
    public static function getSubscribedEvents()
    {
        return [
            'user.created' => 'onUserCreated',
        ];
    }

    public function onUserCreated(UserCreatedEvent $event)
    {
        // Side effects (e.g., send welcome email)
    }
}

Middleware for Commands

Add pre/post-processing logic:

use Ano\CqrsBundle\Command\CommandMiddleware;

class LoggingMiddleware implements CommandMiddleware
{
    public function handle($command, callable $next)
    {
        \Log::info('Command dispatched:', ['command' => get_class($command)]);
        return $next($command);
    }
}

Register middleware in config/packages/ano_cqrs.yaml:

ano_cqrs:
    command_bus:
        middlewares:
            - App\Middleware\LoggingMiddleware

Repository Pattern

Use repositories for data access (integrate with Doctrine or custom implementations):

use Ano\CqrsBundle\Repository\Repository;

class UserRepository implements Repository
{
    public function save(User $user) { /* ... */ }
    public function findByEmail(string $email) { /* ... */ }
}

Gotchas and Tips

Pitfalls

  1. No Built-in Query Support The bundle focuses on commands. For queries, consider pairing with beberlei/doctrine-orm-query-builder or a custom solution.

  2. Event Dispatching Events are not automatically dispatched by the bundle. Use beberlei/lite-cqrs's EventBus or Symfony’s EventDispatcher for event handling.

  3. Middleware Order Matters Middlewares are executed in the order they are registered. Place validation middleware early, logging middleware late.

  4. Dependency Injection Ensure handlers are properly tagged as services in services.yaml:

    services:
        App\Command\Handler\CreateUserCommandHandler:
            tags: ['ano_cqrs.command_handler']
    

Debugging

  • Command Not Found? Verify the handler is tagged as a service and implements CommandHandler. Check ano_cqrs.yaml for misconfigurations.

  • Events Not Triggered? Confirm the event class is properly dispatched (e.g., via EventBus or Symfony’s EventDispatcher).

Extension Points

  1. Custom Command Bus Extend Ano\CqrsBundle\Command\CommandBus to add retry logic or async processing.

  2. Validation Integrate with Symfony Validator:

    use Symfony\Component\Validator\Validator\ValidatorInterface;
    
    class ValidationMiddleware implements CommandMiddleware
    {
        public function __construct(private ValidatorInterface $validator) {}
    
        public function handle($command, callable $next)
        {
            $errors = $this->validator->validate($command);
            if (count($errors)) {
                throw new \RuntimeException('Validation failed');
            }
            return $next($command);
        }
    }
    
  3. Testing Mock the CommandBus in unit tests:

    $commandBus = $this->createMock(CommandBus::class);
    $commandBus->expects($this->once())->method('dispatch');
    

Configuration Quirks

  • Bundle Prefix The bundle uses ano_cqrs as the configuration key. Ensure YAML files reflect this (e.g., config/packages/ano_cqrs.yaml).

  • Doctrine Integration If using Doctrine, configure repositories in ano_cqrs.yaml:

    ano_cqrs:
        repositories:
            App\Entity\User: App\Repository\UserRepository
    
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours