Page parts as Middleware?

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?

just check it:

$app->add(new RunTracy\Middlewares\TracyMiddleware($app));



for routes read default settings

return [
    'settings' => [
        'determineRouteBeforeAppMiddleware' => true,

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.

sorry I misspelled, now check:
load(__construct) as fifo
executed(__invoke) as lifo

Thanks guys, I had a feeling I was going down the wrong path.
I’ve been looking at twig and I think I can do something like:

{% if admin== true%}
    <p>show admin menu</p>
{% endif %}

Is this what you mean by view partials Tim?

{% include ‘header.html’ %}
{% include ‘footer.html’ %}


one layout instead 2 include

<!DOCTYPE html>

     <!-- Page Content -->
    {% block content %}{% endblock content %}
    <!-- /.Page Content -->


html only inside blocks

{% extends 'Layout.html.twig' %}

{% block content %}
    <div class="container">
{% endblock content %}

also set in layout blocks meta, title, css, js
limited only by fantasy

@1f7 wow that seems like it could come in handy, thanks!

I’ve been going down this route. Still stuck in the old PHP way of doing it I guess :slight_smile:

$app->get('/about',function($request,$response) {
    $data = array(
	'pageTitle' => 'About Us',
	'page' => 'about.html'
    return $this->view->render($response,'template.html',$data);

And for my template:

<title>{{ pageTitle }}</title>

{% include page %}


Not sure if there is a downside or overhead to doing it this way, but it’s been working quite well for a while now.