Middlewares can be used to create certain checks before running the entire webapplication. When registered, the type of non route based middlewares run automatically.
Middlewares can be registered inside the /middleware/register/Middleware.php file. Type of non route based middleware should be registered inside the $middlewares property. Type of route middleware should be registered inside the $routeMiddleware property. The key value should be some sort of alias. For the type of route based middleware, this alias can be used inside your routes to refer on the registerd middleware later. The value should be the middleware class name without the php extension.
<?php
namespace middleware\register;
class Middlewares {
public $middlewares [
'alias' => 'ExampleMiddleware',
'alias' => 'ExampleMiddleware'
];
public $routeMiddlewares [
'alias' => 'ExampleMiddleware',
'alias' => 'ExampleMiddleware'
];
}
Middlewares should be created inside the /middleware folder. All created middleware should have a contructor method with at least one parameter. The parameter should be returned as a function.
<?php
namespace middleware;
class ExampleMiddleware {
public function __construct($run) {
return $run();
}
}
The route should be placed in between the function to restrict the route.
<?php
use core\routing\Route;
use core\http\Middleware;
Middleware::route('alias', function() {
new Route(['GET' => '/example'], ['ExampleController' => 'example']);
});
The key value should be the registered middleware alias name and the value can be any value.
<?php
use core\routing\Route;
use core\http\Middleware;
Middleware::route(['alias' => 'value'], function() {
new Route(['GET' => 'example'], ['ExampleController' => 'example']);
});
This extra value can now be applied inside the middleware.
<?php
namespace middleware;
class ExampleMiddleware {
public function __construct($run, $value) {
return $run();
}
}