Middlewares

What is a Middleware?

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.

At a Glance

You can have middlewares for your MightyPHP application. The middlewares reside in the Middlewares folder.

<?php
namespace 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.

Generating Middleware

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.

Middleware in Router

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.

<?php
use 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:

<?php
use 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");

Multiple Middlewares

You could also administer multiple middlewares into a route or route scope.

<?php
use 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.