I wanted to add my remarks to an old thread I just saw (Slim 4 Content Length Middleware position) but I didn’t dare to resurrect a six month topic.
At Content Length Middleware we can read:
This middleware should be placed on the center of the middleware stack so it gets executed last.
Er… The center of a stack?
I’ve always found this extremely confusing and I eventually added this on top of my index.php
:
/*
* ╭── $app->run() ──╮
* │ │
* │ ╲│╱
*/
This is to remind me that middleware, to my eyes, runs twice and in inverse order: one time to process the request (bottom to top) and a second one to process the response (top to bottom). Yes, I know it’s only invoked once but that’s how it feels to my intuition:
public function exampleMiddleware(Request $request, RequestHandler $handler): Response
{
// Optionally do stuff with $request (first run)
$response = $handler->handle($request);
// Optionally do stuff with $response (second run)
return $response;
}
I’ve made my ContentLengthMiddleware()
the last being add()
ed so it’s the outer layer of the onion and the last one to process the response. That fixed some rare intermittent bugs where I couldn’t use the output due to incorrect Content-Length upon middleware making changes to response body.
I’ve no idea if this is what docs mean but I understand it doesn’t make sense to calculate response body length until everybody else is finished fiddling with it.
Is my overall reasoning unusual, misguided or wrong in some way?