Middleware type, and return type

Hello All, I would like to ask 2 questions about use of middlewares in slim. My questions will be about these usages;

slimphp/Slim-Skeleton usage:

Official docs usage:
https://www.slimframework.com/docs/v4/concepts/middleware.html#invokable-class-middleware-example

<?php
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Slim\Psr7\Response;

class ExampleBeforeMiddleware
{
    /**
     * Example middleware invokable class
     *
     * @param  ServerRequest  $request PSR-7 request
     * @param  RequestHandler $handler PSR-15 request handler
     *
     * @return Response
     */
    public function __invoke(Request $request, RequestHandler $handler): Response
    {
        $response = $handler->handle($request);
        $existingContent = (string) $response->getBody();
    
        $response = new Response();
        $response->getBody()->write('BEFORE' . $existingContent);
    
        return $response;
    }
}

Way to impelement
Both are official, but from different up to date sources. However, skeleton-one implements Middeware interface thus process() method is implemented, example usage in the docs is also a class middleware yet do not implements any interface and called via __invoke() method. I would like to learn what are the exact difference between this two usages.

Returning Response
The other question is how they return response; usage in the skeleton returns the response handled by the handler, the other is create a new Response object inline and return the new response. I know in some cases it is needed to create new Response from existing one, but again what are the difference and advantage/disadvantage of it.

I looked them up online but could find any useful answers.

Thank you in advance.

P.S.: Currently slim/slim package’s 4.10 version is installed, and the project based on slim/slim-skeleton composer package.

Both types of middleware are supported by Slim, the PSR-15 MiddlewareInterface with the process method and the invokable class with the __invoke method. The difference from a usage perspective is that the invokable class is not a real “standard”, like the PSR-15 interfaces. If you plan to use your middlewares in other projects or packages, then better use the PSR-15 MiddlewareInterface for all your middlewares. It is also generally recommend to use the MiddlewareInterface.

Returning Response: There is no advantage or disadvantage, because it depends on the use case. One aspect is whether it’ s an inbound or outbound middleware, or even both.

1 Like