Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Created September 10, 2019 09:28
Show Gist options
  • Save kobus1998/8d4a2ce9225d4ba8cc2e5fe564917e24 to your computer and use it in GitHub Desktop.
Save kobus1998/8d4a2ce9225d4ba8cc2e5fe564917e24 to your computer and use it in GitHub Desktop.
Simple Command bus
<?php
interface Command
{
public function handle();
}
class CommandBus
{
protected $events;
private function invoke($call)
{
if (is_callable($call)) {
return $call();
}
return call_user_func($call);
}
public function handle($call)
{
$this->invokeListener('received');
try {
$this->invoke($call);
$this->invokeListener('success');
} catch (\Exception $e) {
$this->invokeListener('error');
}
}
public function addListener($type, $call)
{
$this->events[$type][] = $call;
return $this;
}
public function invokeListener($type)
{
if (!isset($this->events[$type]) || empty($this->events[$type])) {
return $this;
}
try {
foreach($this->events[$type] as $call) {
$this->invoke($call);
}
} catch (\Exception $e) {
}
return $this;
}
}
$bus = new CommandBus();
$bus->addListener('received', function () {
echo "received\n";
});
$bus->addListener('success', function () {
echo "success\n";
});
$bus->addListener('error', function () {
echo "error\n";
});
$bus->handle(function () {
echo "success call\n";
});
$bus->handle(function () {
echo "throwing an exception\n";
throw new \Exception('errr');
});
class UsesClass implements Command
{
public function handle()
{
echo "this uses a class as call\n";
}
}
$bus->handle([new UsesClass, 'handle']);
/*
received
success call
success
received
throwing an exception
error
received
this uses a class as call
success
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment