Skip to content

Instantly share code, notes, and snippets.

@alle
Forked from oqq/CommandMiddleware.php
Created March 17, 2018 16:27
Show Gist options
  • Save alle/3cc78a01e0a3204480b573ca85c2d9f1 to your computer and use it in GitHub Desktop.
Save alle/3cc78a01e0a3204480b573ca85c2d9f1 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