PHP code example of remotelyliving / php-command-bus

1. Go to this page and download the library: Download remotelyliving/php-command-bus library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

remotelyliving / php-command-bus example snippets


$resolver = Resolver::create($serviceContainer) // can locate in service container
    ->pushHandler(Commands\ReserveRoom::class, new Handlers\ReserveRoom()) // can locate in a local map {command => handler}
    ->pushHandlerDeferred(Commands\Checkout::class, fn() => new Handlers\Checkout()); // can locate deferred to save un unnecessary object instantiation


$resolver = Resolver::create($container);
$commandBus = CommandBus::create($resolver, $psr14EventDispatcher | null)
    ->pushMiddleware($myMiddleware1);

$command = new Commands\ReserveRoom(123);
$commandBus->handle($command);

class ReserveRoom
{
    private User $user;

    private Room $room;

    public function __construct(User $user, Room $room)
    {
        $this->user = $user;
        $this->room = $room;
    }

    public function getUser(): User
    {
        return $this->user;
    }

    public function getRoom(): Room
    {
        return $this->room;
    }
}

class ReserveRoom implements Interfaces\Handler
{
    public function handle(object $command, Interfaces\CommandBus $bus)
    {
        $bus->handle(new Commands\MarkRoomAsReserved($command->getRoom()));
        $bus->handle(new Commands\CompleteInvoiceForRoom($command->getUser(), $command->getRoom()));
         
        yield new Events\RoomWasReserved();
    }
}
public function __invoke(Interfaces\Command $command, callable $next);