Created
November 13, 2017 09:35
-
-
Save oqq/98080ed92b465e323b2c68ec0ae11f42 to your computer and use it in GitHub Desktop.
simple command middleware implementation using prooph components
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 | |
declare(strict_types = 1); | |
namespace Acme\Middleware; | |
use Interop\Http\ServerMiddleware\DelegateInterface; | |
use Interop\Http\ServerMiddleware\MiddlewareInterface; | |
use Prooph\Common\Messaging\MessageFactory; | |
use Prooph\Psr7Middleware\MetadataGatherer; | |
use Prooph\ServiceBus\CommandBus; | |
use Psr\Http\Message\ResponseInterface; | |
use Psr\Http\Message\ServerRequestInterface; | |
use Zend\Diactoros\Response\JsonResponse; | |
final class CommandMiddleware implements MiddlewareInterface | |
{ | |
private $commandBus; | |
private $commandFactory; | |
private $metadataGatherer; | |
private $commands; | |
public function __construct( | |
CommandBus $commandBus, | |
MessageFactory $commandFactory, | |
MetadataGatherer $metadataGatherer, | |
array $commands | |
) { | |
$this->commandBus = $commandBus; | |
$this->commandFactory = $commandFactory; | |
$this->metadataGatherer = $metadataGatherer; | |
$this->commands = $commands; | |
} | |
public function process(ServerRequestInterface $request, DelegateInterface $delegate): ResponseInterface | |
{ | |
$command = $request->getAttribute('command'); | |
$commandClass = $this->commands[$command]; | |
$command = $this->commandFactory->createMessageFromArray($commandClass, [ | |
'payload' => (array) $request->getParsedBody(), | |
'metadata' => $this->metadataGatherer->getFromRequest($request), | |
]); | |
$this->commandBus->dispatch($command); | |
return new JsonResponse(['success' => true]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment