Last active
August 29, 2015 14:06
-
-
Save jenkoian/c9427dbf3979125f5b4c to your computer and use it in GitHub Desktop.
Symfony container command bus example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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