Skip to content

Instantly share code, notes, and snippets.

@oqq
Created November 13, 2017 09:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save oqq/98080ed92b465e323b2c68ec0ae11f42 to your computer and use it in GitHub Desktop.
Save oqq/98080ed92b465e323b2c68ec0ae11f42 to your computer and use it in GitHub Desktop.
simple command middleware implementation using prooph components
<?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