1

I've been thinking about the most optimal way to implement middleware in my web application and it got me thinking, how is middleware any different from events?

Let's say that before a controller gets executed I want to verify that the IP from which the request is coming from is not blacklisted. Do I create a new middleware or register a listener for a OnRequest or BeforeController event? Don't these two achieve the same thing? They both get executed before the controller and have the ability to take actions based on the contents of the request.

I suppose they differ in the way that middleware is more focused around the before/after controller idea where as events can be used for all kinds of things in the entire application.

There's also the fact that you possibly don't want to execute that IP check on every request so you'd have to have a way to exclude/include the check for certain controllers. This would be somewhat hacky to do with events since the whole idea behind them is that their listeners get called every time that event gets fired.

Are these the only differences though or there's something I'm missing?

0

No, you're not missing anything.

Frameworks evolve, and new paradigms are added, because of their growing popularity, but older paradigms are kept to remain backwards compatible.

Therefore, you can still use the events or go with middleware.

Given the popularity of a middleware approach to perform pre-request/post-response actions, it is better to stick with it for new projects. If you maintain a legacy project which uses events, you may either continue to use events, or migrate the entire code base to middleware. Never use both approaches in the same project: this will necessarily create ambiguity for the maintainers who will expect to find an action in a form of an event when it's actually done in a form of a middleware, or the opposite.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.