Thanks to visit codestin.com
Credit goes to bowphp.com

Skip to main content
Version: CANARY 🚧

HTTP Middlewares

Introduction​

About middlewares

Middlewares provide a convenient mechanism for filtering the HTTP requests entering your application.

For example, you can write a middleware to check whether a user is logged in and then take an action accordingly. You can run code before and after your Bow application to manipulate the Request and Response objects however you see fit.

asciicast

How it works​

Different frameworks use the middleware system in different ways. Bow adds a middleware as a queue on top of your main application. Each new middleware layer is added to the existing middleware queue. The queue structure expands outward as additional intermediate layers are added.

When you run the Bow application, Request objects traverse the middleware structure from the outside in. They first enter the outermost middleware, then the next outermost middleware (and so on), until they reach the application itself. Once the Bow application has dispatched the appropriate route, the resulting Response object leaves the Bow application and is serialized into an HTTP response that is sent back to the HTTP client.

The only strict condition is that a middleware must return a value other than null. Each middleware must call the next middleware and pass it the Request objects as arguments via the $next method.

Default middlewares

Bow includes several default middlewares such as the csrf and auth middlewares.

Adding a middleware​

To add a middleware, use the add:middleware command of php bow:

php bow add:middleware IpMiddleware
Middleware location

By default, all middlewares are saved in the app/Middlewares folder.

The middleware we just added will check the client's IP address, and if its address equals 127.0.0.1, we will consider the application to be in development mode.

But first, let's look at the contents of the IpMiddleware file. The process method is what runs the middleware, and the callable is what runs the next middleware.

app/Middlewares/IpMiddleware.php
namespace App\Middlewares;

use Bow\Http\Request;
use Bow\Middleware\BaseMiddleware;

class IpMiddleware implements BaseMiddleware
{
/**
* Middleware entry point function.
*
* @param Request $request
* @param callable $next
* @param array $args Optional parameters (see "Parameters" below)
*/
public function process(Request $request, callable $next, array $args = []): mixed
{
return $next($request);
}
}

For our example we will then have the following process:

public function process(Request $request, callable $next, array $args = []): mixed
{
if ($request->ip() == '127.0.0.1') {
return "MODE DEV";
}

return $next($request);
}
The BaseMiddleware contract

The Bow\Middleware\BaseMiddleware interface formalizes the signature. Your middlewares can implement it (recommended) or simply define a compatible process() method.

Registering a middleware​

Generally, registration is done in the app/Kernel.php file with a key that identifies it.

public function middlewares()
{
return [
...
'ip' => \App\Middlewares\IpMiddleware::class
...
];
}

It is also possible to add middlewares globally in the application. This is done in the routes file with the middleware method on $app, which returns an instance of \Bow\Router\Router::class. All routes defined with this instance will inherit the specified middlewares.

$router = $app->middleware(\App\Middlewares\IpMiddleware::class);
$router->get('/', 'HomeController::index');

// Or
$router = $app->middleware([
\App\Middlewares\IpMiddleware::class,
\App\Middlewares\OtherMiddleware::class,
]);
$router->get('/', 'HomeController::index');

Using middlewares​

Applying middlewares

After defining a middleware in the app/Kernel.php file, you can apply it to your routes.

$app->get('/', 'HomeController::index')->middleware('ip');
$app->get('/', 'HomeController::index')->middleware(['ip', 'autre']);

// You can also pass a FQCN directly without declaring an alias:
$app->get('/', 'HomeController::index')
->middleware(\App\Middlewares\IpMiddleware::class);

// Via the route() method:
$app->route([
'path' => '/',
'method' => 'GET',
'handler' => 'HomeController::index',
'middleware' => ['ip', 'autre']
]);

Middleware parameters​

You can pass parameters to a middleware by appending them after the name, separated by a : (then commas for multiple values):

// One parameter
$app->get('/admin', 'AdminController::index')->middleware('role:admin');

// Multiple parameters
$app->get('/api/posts', 'PostController::index')->middleware('throttle:60,1');

The values are available in $args:

app/Middlewares/RoleMiddleware.php
namespace App\Middlewares;

use Bow\Http\Request;
use Bow\Middleware\BaseMiddleware;

class RoleMiddleware implements BaseMiddleware
{
public function process(Request $request, callable $next, array $args = []): mixed
{
// 'role:admin,editor' => $args === ['admin', 'editor']
$allowed_roles = $args;

if (!in_array($request->user()?->role, $allowed_roles, true)) {
return response()->json(['error' => 'Forbidden'], 403);
}

return $next($request);
}
}
Parsing

The name and the parameters are separated by the first : encountered (explode(':', $middleware, 2)). The values are then separated by commas. No casting is performed β€” your parameters always arrive as strings.

Is something missing?

If you run into problems with the documentation or have suggestions to improve the documentation or the project in general, please open an issue for us, or send a tweet mentioning the Twitter account @bowframework or directly on github.