Upgrade v3 to v4 : how should I adapt my middleware?

Hi,

I’m working on migrating my slim v3 (rest backend) to v4.
The upgrade “guide” is sooo light considering all the changes :hushed:

MiddleWare have changed of interface.

Any tips to convert from the v3 interface to the v4?

I use middleware to implement authentication:

Thanks,
Thomas.

Well, I hope that the following is enough:

<?php
require '../../vendor/autoload.php';
use \RedCrossQuest\Middleware\AuthorisationMiddleware;
$app->add( new AuthorisationMiddleware($app) );

To

<?php
declare(strict_types=1);
require '../../vendor/autoload.php';

use Slim\App;
use \RedCrossQuest\Middleware\AuthorisationMiddleware;

return function (App $app) {
 $app->add(AuthorisationMiddleware::class);
};

The middleware must implement Psr\Http\Server\MiddlewareInterface
And the signature of the main method changed from

public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)

To
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface

On you middleware class :

Add this :

use Psr\Http\Server\MiddlewareInterface;

class AuthorisationMiddleware implements MiddlewareInterface

Update the __invoke methode to the “process” signature

return $next($request, $response);

Should be change to

return $handler->handle($request)

For denying a request :

$response500 = $response->withStatus(500);
…
return $response500;

Change it to :

$response500 = (new Response())->withStatus(500);
…
return $response500;