PHP Middleware – Are Hooks Subsumed by Slim Framework Middleware?

eventhooksmiddlewarePHP

I've been using the Slim Framework (v2) for a little while now to develop my user management system.

They recently released Slim 3, and according to the upgrade guide,

Slim v3 no longer has the concept of hooks. Hooks were removed as they duplicate the functionality already present in middlewares. You should be able to easily convert your Hook code into Middleware code.

I'm not quite sure if I believe this. Slim's middleware allows you to modify the request before it hits your main application, or modify the response before it is sent out to the client.

However, this says nothing of modifying the behavior of the application itself, which hooks can do easily – the application simply anticipates points in the code where someone might want to modify the behavior, and call applyHook accordingly.

From what I can tell, the only way to modify the core behavior of an application via middleware is via exceptions – the middleware throws an exception, which the core application catches, and then does something else. But this seems to me an abuse of the framework, and I have a hard time believing that this is what they mean.

Do hooks really "duplicate the functionality already present in middlewares"?

Best Answer

From my understanding of hooks this is true. The way I understand hooks it that you can execute some code at a predefined point during the execution flow. Afterwards the application continues as if nothing happened. This is very abstract so I would like to express this using an example:

Lets say you can execute code when an before_authentication hook is encountered. Maybe you would like to initialize sessions before authentication and would therefore do this here. This can also be done through middleware.

Lets say you have a middleware component which handles authentication. Each middleware is defined inside an array and are executed in the defined order. You would then insert your InitializeSessionMiddleware component just before AuthenticationMiddleware is defined in the array.

Both of these solutions would work, but since Slim (AFAIK) is very HTTP focused, it would be more appropriate to write this as middleware.

Please keep in mind this is my understanding of midddleware and hooks. If you would like to modify how the application works at predefined points, I would look into exposing some callbacks, which has a predefined structure (interface?) unique for that specific point. This callback could be changed if the structure is correct.

I hope this can help you, happy coding.

Related Topic