Restore missing Command Bus in new Laravel versions
Tags: php, laravel, cqrs
Published: 2022-03-22 00:21:55


Command Bus is a very powerful pattern, which can help you in decoupling your application modules. You can in an easy way separate small actions, and trigger them using a single dependency called CommandBus.

The cause why this pattern is able to decouple your modules is that actually, the module that is dispatching the command doesn’t have to care about the actual implementation of the action. No matter if that’s a simple DB query, complicated calculations, or calling another remote service. Using this pattern will help you also if you want to implement one of [CQS](https://martinfowler.com/bliki/CommandQuerySeparation.html) and [CQRS](https://martinfowler.com/bliki/CQRS.html) patterns.

## The CommandBus pattern

This pattern requires three elements:

**Command** - is a small class that name should describe the action that you want to call. I should store all data required to execute actual action.

```php
class ReserveResource
{
    public function __construct(
        private ResourceId $resourceId,
        private Period $period
    ) {}
    
    public function getId(): ResourceId
    {
        return $this->resourceId;
    }

    public function getPeriod(): Period
    {
        return $this->period;
    }
}
```

**Handler** - it's the actual implementation of the action. It should implement `handle` or `__invoke` method that is handling a Command.

```php
class ReserveResourceHandler
{
    public function __construct(
        private ResourceRepository $resourceRepository
    ) {}

    public function handle(ReserveResource $reserveResource): void
    {
        $resource = $this->resourceRepository->find($reserveResource->getId());
        $resource->reserve($reserveResource->getPeriod());
        $this->resourceRepository->save($resource);
    }
}
```

**Bus** - it’s the last element of this puzzle. This is the element that keeps all definitions of relations between Commands and Handlers, and it’s also able to run right Handler. That’s the part that is generic and you can use ready implementations, so implementing that on your own doesn’t make sense.

Example usage of CommandBus:

```PHP
$bus = new CommandBus(); // Create new CommandBus instance
$bus->map([ReserveResource::class, ReserveResourceHandler::class]); // Map command and handler

// Create command
$reserveResource = new ReserveResource(
    'affa2136-5b90-4f7c-933e-73cffc39f1d9',
    new Period('2020-12-06 15:30', '2020-12-06 16:30')
);

$bus->dispatch($reserveResource); // Dispatch command
```

## Bus implementation

There are some PHP, ready implementations of CommandBus. One of them is the component of the popular Symfony framework, it’s called [Messenger](https://symfony.com/doc/current/components/messenger.html). You can also use one of The PHP League packages called [Tactician](https://tactician.thephpleague.com/). But if you’re programming in Laravel and you need simple as possible CommandBus implementation, there is an option to use the existed part of the framework.

Older versions of Laravel had an implementation of [CommandBus out of the box](https://laravel.com/docs/5.0/bus#creating-commands). Today the name of this feature was changed, and it’s split to Events and Jobs / Queues, but the event can be queued too…??? I do not fully understand this separation, but I know it may be helpful when you need to implement something quickly.

Ok, never mind let's take a look at Laravel 5 documentation:

```php
Bus::dispatch(
    new PurchasePodcast(Auth::user(), Podcast::findOrFail($podcastId))
);
```

Ok, this is a usage of Facade called `Bus`. Let's try to find out if this class is still available in Laravel code. [Here it is](https://laravel.com/api/8.x/Illuminate/Support/Facades/Bus.html) still available.
Ok, but I don't like facades, I think that the name of them is badly used, and Laravel facades are like hidden dependencies of your classes. It's always better to inject the dependency from the DI container. So I was investigating the code, and I got to the `Illuminate\Bus\Dispatcher` class. And that's the part of Laravel framework that is implemented like Command Bus functionality.

I’m not recommending using this class directly. This class is not specified in documentation and it could be removed or replaced one day in Laravel (it probably won't). Also, you may want to improve the functionalities of your command bus, so using this one directly, will cause the problem in replacing it in all the places of usage.

Let's create the Adapter that will be also our safe proxy. But also do not include our Adapter directly. Let's use an interface that will allow us to juggle with implementations.

```php
interface CommandBus
{
    public function dispatch($command): void;
    public function map(array $map): void;
}
```

And next the implementation:

```php
use Illuminate\Bus\Dispatcher;

class IlluminateCommandBus implements CommandBus
{
    public function __construct(private Dispatcher $bus) {}

    public function dispatch($command): void
    {
        $this->bus->dispatch($command);
    }

    public function map(array $map): void
    {
        $this->bus->map($map);
    }
}
```

Next, we can declare it in the DI container in the service provider. Remember to register it as a Singleton. It's important to get the same instance of the bus in every place of the application.

```php
public function register()
{
    $this->app->singleton(CommandBus::class, IlluminateCommandBus::class);
}
```

Now you can define the Commands and Handlers map, and the Command Bus it's ready to use.

So first register

```php
public function register()
{
    /** @var CommandBus $bus */
    $bus = $this->app->make(CommandBus::class);
    $bus->map([
        ReserveResource::class => ReserveResourceHandler::class,
        TurnOnResource::class => TurnOnResourceHandler::class,
        WithdrawResource::class => WithdrawResourceHandler::class,
        CreateResource::class => CreateResourceHandler::class,
    ]);
}
```

and use

```PHP
class ReservationController
{
    public function __construct(private CommandBus $bus) {}

    public function reserve(int $id, ReserveRequest $request): void
    {
        $command = ReserveResource::fromRaw(
            $id,
            $request->get('from'),
            $request->get('to')
        );

        $this->bus->dispatch($command);
    }
}
```