A middleware is what stands between your application and the world-wide-web. If you wish to enforce certain kinds of extra security, checking, authentication, or data massaging, this is where you can give it a go.
You can have middlewares for your MightyPHP application. The middlewares reside in the Middlewares folder.
<?phpnamespace Application\Middlewares;​use MightyCore\Middleware;use MightyCore\Vault\Routing\VerifyCsrf as RoutingVerifyCsrf;​class VerifyCsrf extends Middleware{public function administer(){$verifyCsrf = new RoutingVerifyCsrf();$verifyCsrf->verify();}}
You may then administer this middleware accordingly in the routing blocks.
If you are lazy, we provide a boilerplate generator of which you can use to quickly set up a middleware.
php mighty make:middleware YourMiddleware
This will generate a boilerplate middleware, called YourMiddleware
in the Application/Middlewares
folder.
So now that you have a middleware, how do we get it into a router? You can administer middlewares to routers using the use()
method.
<?phpuse MightyCore\Routing\Router;​$index = new Router('/');$index->use("VerifyCsrf");$index->get('/', '[email protected]')->name('home');
This way, we are administering the VerifyCsrf middleware to the entire route scope. There will be times when you would like to only administer to one or a few of the routes in a route scope. You can do it individually as well:
<?phpuse MightyCore\Routing\Router;​$index = new Router('/');$index->get('/', '[email protected]')->name('home');​// We would like to only use VerifyCsrf middleware on one particular route.$index->get('/', '[email protected]')->name('foo')->use("VerifyCsrf");
You could also administer multiple middlewares into a route or route scope.
<?phpuse MightyCore\Routing\Router;​$index = new Router('/');$index->use(["VerifyCsrf", "Foo"]);
By passing an array into the use()
method, the middlewares will be administered according to the array sequence.