Middleware is a type of controller, but its primary purpose is not to provide the expected response to the user (although middleware can return error texts), but to perform specific tasks before or after that response is generated.
Unlike a controller, this middleware can be assigned not only to a route but also to a group of routes. Both can have multiple different middleware (or even the same ones, if needed).
For example, user authorization can be implemented in middleware and applied to a group of routes where it is needed. Before the execution of the controller or any other primary action attached to the route, the current user and their authorization status will be determined.
Otherwise, the middleware class will hand over execution to another controller, return an error, or redirect to another route, depending on the implementation.
When the middleware() method (options after() or before()) is applied in a route, it takes a data argument. This is another difference from the controller; a data array can be passed to this argument, which will then be available in middleware. The array data is accessible in the method Hleb\Static\Router::data() or via the container.
The middleware class must inherit from Hleb\Base\Middleware.
Typically, the purpose of the called method of this class is not to return anything, but to validate conditions. However, in some cases, returning a value is allowed.
string|int|float - these types will be converted to a string and output as text in their original form.
array - the returned array will be converted into a JSON string. After this, further execution is terminated.
bool - if false is returned, it is equivalent to stopping further execution.
Besides copying the demonstration file DefaultMiddleware.php and modifying it, there is another simple way to create the required class using a console command.
$php console --add middleware ExampleMiddleware
This command will create a new template /app/Middlewares/ExampleMiddleware.php.
You can use another suitable name for the class.
The HLEB2 framework also allows you to create a custom template by default for this command.