I implemented a middleware class to easily add header / footer to my application. I was thinking, that maybe this would also be a great way to add certain menus to specific pages/routes.
The reason I’m asking is: I quickly wrote up a class for menu middleware and I can already see some problems in where it is getting placed. Is middleware guaranteed to be called in order? It seems to go backwards up the chain so is it reliable? or…
I’m I thinking about this incorrectly? Would a tempting solution be better and if so how could I implement one based on routes and user permission levels?
I think adding page parts as middleware will become a huge headache. I’d use view partials and build the view from those partials. Personally, I like Twig.
The order middleware is applied can be confusing, however it is called in a specific order. See How Does Middleware Work for more information, but note the sentence “The last middleware layer added is the first to be executed.”
Also note that middleware executes twice, once on its way down to the app and ones again on the way back out. The code before calling next() executes on the way towards $app and the code after executes on the way back out.
But personally, I wouldn’t add view parts to Middleware. I think that will become very difficult to manage.