With the exception of /anonymous/news, every valid request to Mabel has to go through the "check if the authorization header is in the request, get the header value, is the value an empty string, yada yada yada" rigmarole.
Initially, I put this authorization functionality into the beginning of the action() methods of the controllers I was building out. Eventually, I noticed commonalities and moved that code up to the base class that all controllers inherit.
It became clear though that I was going to end up in a situation where controllers of the same authorization case would contain identical code at the start of their action methods. However, I would not be able to move that code up to the base class without implementing some really 'clever' code. And as I always say, "there's good clever and there's bad clever" and this would clearly have been a case of the bad flavor.
As it so happens, this is the scenario where middleware really shines. Middleware is simply the idea that I can tell Slim (or other similar micro-frameworks) that I want code to execute before or after the action in a controller. In some frameworks you explicitly state "I want this code to execute before" or "I want this code to execute after". In Slim 4 you sort of just wrap your middleware around the action and handle the 'before or after' part in the middleware itself.
Ultimately, I was able to move all of the repetitive code out of the controllers entirely, leaving behind just the code that pertains specifically to that controller's action.
So yeah. Yay middleware.
No comments:
Post a Comment