0

I'm practicing with CQRS and making my own implementation of CommandBus to see how it works.

What I want to do? I would like to have my own framework where I create my bootstrapping to instantiate my CommandBus with my array where I map each command with its handler. My intention was to do the following:

I create the CommandBus and instantiate it in my app.php

CommandBus:

final class CommandBus {`

    private array $handlers;
    
    public function __construct()
    {
        $this->handlers = [];
    }
    
    public function addHandler($commandName, $handler) {
        $this->handlers[$commandName] = $handler;
    }
    
    public function handle($command) {
        $commandHandler = $this->handlers[get_class($command)];
        if($commandHandler === null) {
            throw new \http\Exception\InvalidArgumentException();
        }
    
        return $commandHandler->handle($command);
    }

}

app.php:

$commandBus = new CommandBus();

$commandBus->addHandler($commandName, $handler);

Controller:

final class Controller {

    public function __construct()
    {}
    
    public function action() {
        //...
        $commandBus->handle($command);
        //...
    }

}

The problem is that I can't use the $commandBus variable inside my controller. What would be the best way to have that variable always available and have access to my array of handlers?

Kirk Beard
  • 8,890
  • 12
  • 43
  • 46
  • Personally, I’d probably make `CommandBus` a [singleton](https://stackoverflow.com/questions/24852125/what-is-singleton-in-php). That way, your app will only have one instance of it and you can get access to that instance from anywhere. – rickdenhaan Mar 25 '22 at 18:56

0 Answers0