Middleware Before *and* After Determining Route


#1

I’m trying to understand the process around middleware execution with Slim 3. If I understand correctly, it’s something like:

→ App Middleware
→ determine route
→ Route Middleware

and one can set determineRouteBeforeAppMiddleware, which makes it:

→determine route
→ App Middleware
→ Route Middleware

Unfortunately, neither is sufficient. I’m trying to determine whether it’s possible to specify some app middleware to run before the route is determined, and some after:

→ before-routing App Middleware
→ determine route
→ after-routing App Middleware
→ Route Middleware

This is necessary because some middlewares parse, and potentially manipulate, the Request in ways which would affect routing, while other middlewares depend on the route to make choices.

The only workaround I can imagine is making an artificial “all routes” route group and adding the “post-routing-app-middleware” to that. I’m hoping there’s a happier solution.

Thanks!


#2

Slim middlewares are used to control the request/response flow.
https://www.slimframework.com/docs/v3/concepts/middleware.html

In my case, I use it to add additional steps before and after these flows to show proper information, access, extra information, etc. to the user.

Example 1 (before): get a header’s authorization token (JWT) to know if the user has access to non-public URLs
Example 2 (before): using the previous token I could validate if the user has access to a specific URL using an ACL (Access Control List) component
Example 3 (after): You could minify HTML with a middleware getting the content type and removing comments, extra spaces, etc.

I use Slim and similar frameworks to expose data through Restful API. Check this public project, I think it could be helpful.
https://bitbucket.org/diegoluisr/backend-test/src/master/


#3

Thanks, but I don’t see how this is relevant: my question was about the order+timing of when Slim invokes middleware, and the extent to which that can be controlled; not about the basics of what middleware is in general.


#4

Please check this file.
https://bitbucket.org/diegoluisr/backend-test/src/master/www/html/api/index.php
From line 36 to 60

The first middleware added is the latest being processed, but this depends on when are you returning the response object gotten by the “$next” callable.

return $next($request, $response);

Or

$response = $next($request, $response);