Skip to content

Instantly share code, notes, and snippets.

@jenkoian
Last active August 29, 2015 14:06
Show Gist options
  • Save jenkoian/c9427dbf3979125f5b4c to your computer and use it in GitHub Desktop.
Save jenkoian/c9427dbf3979125f5b4c to your computer and use it in GitHub Desktop.
Symfony container command bus example
<?php
namespace Acme\CommandBus;
use Acme\CommandInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class CommandBus implements CommandBusInterface
{
/**
* @var ContainerInterface $container
*/
protected $container;
/**
* @var CommandNameInflector
*/
protected $commandNameInflector;
/**
* @param ContainerInterface $container
* @param CommandNameInflector $commandNameInflector
*/
public function __construct(ContainerInterface $container, CommandNameInflector $commandNameInflector)
{
$this->container = $container;
$this->commandNameInflector = $commandNameInflector;
}
/**
* @param CommandInterface $command
* @return mixed
*/
public function execute(CommandInterface $command)
{
return $this->getHandler($command)->handle($command);
}
/**
* @param $command
* @return mixed
*/
private function getHandler($command)
{
return $this->container->get($this->commandNameInflector->getHandlerService($command));
}
}
<?php
namespace Acme\CommandBus;
use Acme\CommandInterface;
class CommandNameInflector
{
/**
* @var array
* TODO: Look at tagging handlers and using a compiler pass to neatly handle this.
*/
protected static $handlerServiceMap = [
'FooHandler' => 'acme.handler.foo',
'BarHandler' => 'acme.handler.bar',
];
/**
* @param CommandInterface $command
* @return mixed
*/
public function getHandlerClass(CommandInterface $command)
{
return str_replace('Command', 'Handler', get_class($command));
}
/**
* @param CommandInterface $command
* @return mixed
*/
public function getHandlerService(CommandInterface $command)
{
$class = $this->getHandlerClass($command);
$reflect = new \ReflectionClass($class);
return static::$handlerServiceMap[$reflect->getShortName()];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment