How to Structure Middleware in Slim Framework for Clean Code:?

Hi everyone,

I have been working with Slim Framework for a while and I love its simplicity and flexibility. However…, as my project grows; I am finding my middleware logic becoming a bit messy and hard to maintain.

Here are a few specific challenges I am facing:

Middleware chaining :- How to efficiently chain multiple middlewares without making the code look cluttered: ??
Reusability :- What’s the best way to make middleware reusable across different routes: ??
Order of execution :- How do you manage middleware execution order when dealing with complex applications: ??

I am looking for tips or best practices that align with Slim’s principles of being lightweight and efficient. If you have encountered similar challenges or have insights on how to keep middleware clean and maintainable…, I would greatly appreciate your advice. I have also searched on the forum for the thread related to my query and I found this one thread https://discourse.slimframework.com/t/models-middleware-philosophy-architecture-devops but coludn’t get any help.

Looking forward to learning from the community !!

With Regards,
Marcelo Salas

Hi @marcelosalas

I follow and recommend these practices to keep middlewares clean, reusable, and maintainable:

  1. Use classes (instead of callbacks)
  2. Use the $app->add(...); method to add middleware
  3. Use the ::class constant to register middleware: $app->add(MyMiddleware::class);
  4. Use a DI container to configure the middleware.

The ::class constant in combination with a DI container is a powerful tool, because you can handle all the instantiation and configuration in one place, the DI container.

The order of execution is handled by how you add the middleware into the stack.
In Slim 4 middleware added earlier is executed later (LIFO - Last In, First Out).

$app->add(Middleware1::class);
$app->add(Middleware2::class);

Execution order: Middleware2 → Middleware1.

So the direction goes from “down to up”. Note that this might order change in Slim 5 to FIFO (first in, first out).