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.