Skeleton Handler vs Middleware

Using the skeleton as guideline, Slim v4, how do I know if I should write some middleware or a handler?

/src/Application/Handlers
/src/Application/Middleware

In slim v3 I feel like I just had a chunk of middleware that I mapped at the end of a route, it checked their JWT authentication and so on.

When I look at the skeleton, I feel like my existing code should possibly be broken into separate files.

1 Like

Middlware by default.

Handlers are very special here and can be used for PHP specific error handling.

Maybe it was this line that was tripping me up.

    return $handler->handle($request);

Is it best practice to always create the middleware response by sending the modified request through the handle() function?

A Middleware could also produce a response on its own.

In cases where the middleware cannot produce its own response, it can delegate to the request handler to produce one (by the ServerRequestFactory).

In the most cases the middleware is just manipulating and returning the response produced by the request handler.

Examples:

// Straight delegation:
return $handler->handle($request);
// Capturing the response to manipulate:
$response = $handler->handle($request);

// manipulate the response
$response = $response->withHeader('X-Foo-Bar', 'baz');

return $response;

Read more about PSR-15