Skip to content

Instantly share code, notes, and snippets.

@doMynation
Created December 17, 2015 23:31
Show Gist options
  • Save doMynation/e389c61eea6e07f3a408 to your computer and use it in GitHub Desktop.
Save doMynation/e389c61eea6e07f3a408 to your computer and use it in GitHub Desktop.
BasicCommandBus
<?php
namespace Framework\Bus;
use Interop\Container\ContainerInterface;
final class BasicCommandBus implements CommandBusInterface
{
/**
* @var \Framework\Bus\Middlewares\CommandBusMiddleware
*/
private $middlewareChain;
/**
* @var ContainerInterface
*/
private $container;
public function __construct(ContainerInterface $container, array $middlewares)
{
$this->middlewareChain = $this->buildMiddlewareChain($middlewares);
$this->container = $container;
}
public function execute(Command $command)
{
// Resolve the handler class
$handler = $this->resolveHandlerClass($command);
// Pass the command and its handler in the middleware chain
return $this->middlewareChain->handle($command, $handler);
}
private function buildMiddlewareChain(array $middlewares = [])
{
if (empty($middlewares)) {
return null;
}
// Fetch the first middleware
$next = array_shift($middlewares);
// Set its next middleware
$next->setNext($this->buildMiddlewareChain($middlewares));
return $next;
}
/**
* Resolves an instance of the handler class
* corresponding to $command.
*
* @param Command $command
*
* @return mixed
* @throws \Exception
*/
private function resolveHandlerClass(Command $command)
{
$reflectionObject = new \ReflectionObject($command);
$shortName = $reflectionObject->getShortName();
$className = $reflectionObject->getNamespaceName() . '\\Handlers\\' . $shortName . 'Handler';
if (!class_exists($className)) {
throw new \Exception("No command handler found for " . $className);
}
// Let the container resolve the instance and inject the
// required dependencies.
return $this->container->get($className);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment