Skip to content

Instantly share code, notes, and snippets.

@jmsfwk
Last active July 13, 2018 10:37
Show Gist options
  • Save jmsfwk/af807b563a1f21437bd021e15c039f00 to your computer and use it in GitHub Desktop.
Save jmsfwk/af807b563a1f21437bd021e15c039f00 to your computer and use it in GitHub Desktop.
PSR-15 Middleware vs HttpKernelInterface implemented as middleware

Different middleware implementations for comparison

PSR-15 Middleware

<?php

use Psr\Http\Server\{MiddlewareInterface, RequestHandlerInterface};
use Psr\Http\Message\{ServerRequestInterface, ResponseInterface};

class Middleware implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // do stuff to the request

        $response = $handler->handle($request);

        // do stuff to the response

        return $response;
    }
}

HttpKernelInterface middleware

<?php

use Symfony\Component\HttpFoundation\{Request, Response};
use Symfony\Component\HttpKernel\HttpKernelInterface;

class Middleware implements HttpKernelInterface
{
    private $kernel;

    public function __construct(HttpKernelInterface $kernel)
    {
        $this->kernel = $kernel;
    }

    public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
    {
        // do stuff to the request

        $response = $this->kernel->handle($request, $type, $catch);

        // do stuff to the response

        return $response;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment