Lumen 5.2 study Notes-HTTP middleware usage

Source: Internet
Author: User
Tags closure http redirect mixed

1. Introduction

HTTP middleware provides a convenient mechanism to filter HTTP requests that enter the application. For example, Lumen contains a middleware to verify whether the user is authorized. If the user is not authorized, the middleware will redirect the user to the logon page. Otherwise, if the user is authorized, the middleware allows the request to proceed to the next step.

Of course, in addition to authentication, middleware can also be used to process more tasks. For example, CORS middleware can be used to add appropriate headers (cross-origin) for the response from the site. Log middleware can record all requests to the site.

All Middleware is stored in the app/Http/Middleware directory.

2. Define middleware

To create a new middleware, you must re-write the handle method in the newly created middleware. In the following middleware, we only allow access routes with age greater than 200. Otherwise, we redirect users to/home:

<? Php

Namespace App \ Http \ Middleware;

Use Closure;

Class OldMiddleware
{
/**
* Return request filter
     *
* @ Param \ Illuminate \ Http \ Request $ request
* @ Param \ Closure $ next
* @ Return mixed
*/
Public function handle ($ request, Closure $ next)
    {
If ($ request-> input ('age') <= 200 ){
Return redirect ('Home ');
        }

Return $ next ($ request );
    }

}

As you can see, if age <= 200, the middleware will return an HTTP redirect to the client; otherwise, the request will be passed. You can call the callback function $ next to pass the request down.

The best way to understand the middleware is to regard the middleware as the "layer" that must be passed before the HTTP request reaches the target. Each layer checks the request and even rejects it completely.

2.1 Before/After middleware

Whether a middleware is executed before or after a request depends on the middleware itself. For example, the following middleware will execute some tasks before processing the request:

<? Php

Namespace App \ Http \ Middleware;

Use Closure;

Class BeforeMiddleware
{
Public function handle ($ request, Closure $ next)
    {
// Execute the action

Return $ next ($ request );
    }
}
However, the middleware will execute the following tasks after the request is processed:

<? Php

Namespace App \ Http \ Middleware;

Use Closure;

Class AfterMiddleware
{
Public function handle ($ request, Closure $ next)
    {
$ Response = $ next ($ request );

// Execute the action

Return $ response;
    }
}

3. Register middleware
3.1 Global middleware

If you want the middleware to be executed during each HTTP request, you only need to put the corresponding middleware class in the $ app-> middleware () Call of the bootstrap/app. Php file:

$ App-> middleware ([
App \ Http \ Middleware \ OldMiddleware: class
]);

3.2 allocate middleware to routes

If you want to allocate middleware to the specified route, you should first in bootstrap/app. the PHP file is assigned to the middleware with a abbreviated key. By default, the $ app-> routeMiddleware () method contains the ingress middleware that comes with Lumen, to add your own middleware, you only need to append it to the end and assign a key to it:

$ App-> routeMiddleware ([
'Old' => 'app \ Http \ Middleware \ OldMiddleware ',
]);
After the middleware is defined in the entry file, you can use the middleware Key in the routing options array to specify the middleware:

$ App-> get ('admin/profile ', ['middleware' => 'auth', function (){
//
}]);
You can specify multiple middleware for a route using arrays:

$ App-> get ('/', ['middleware Ware '=> ['first', 'second'], function (){
//
}]);

4. Middleware parameters

Middleware can also receive additional custom parameters. For example, if an application needs to verify that the user has a specified role before performing an action, it can create a RoleMiddleware to receive the role name as an additional parameter.

The extra middleware parameters are passed into the middleware after the $ next parameter:

<? Php

Namespace App \ Http \ Middleware;

Use Closure;

Class RoleMiddleware
{
/**
* Run the request filter.
     *
* @ Param \ Illuminate \ Http \ Request $ request
* @ Param \ Closure $ next
* @ Param string $ role
* @ Return mixed
* Translator http ://
*/
Public function handle ($ request, Closure $ next, $ role)
    {
If (! $ Request-> user ()-> hasRole ($ role )){
// Redirect...
        }

Return $ next ($ request );
    }

}
Middleware parameters can be specified by separating the middleware name and parameter name when defining a route. Multiple middleware parameters can be separated by commas:

$ App-> put ('post/{id} ', ['middleware Ware' => 'role: editor', function ($ id ){
//
}]);

5. Terminate middleware

Sometimes middleware may need to do some work after the HTTP response is sent to the browser. For example, the Lumen "session" middleware writes the session data to the memory after the response is sent to the browser. To achieve this, define a "Terminator" middleware and add the terminate method to the middleware:

<? Php

Namespace Illuminate \ Session \ Middleware;

Use Closure;

Class StartSession
{
Public function handle ($ request, Closure $ next)
    {
Return $ next ($ request );
    }

Public function terminate ($ request, $ response)
    {
// Store session data...
    }
}

The terminate method will receive requests and responses as parameters. Once you define an end middleware, you should add it to the global middleware list of bootstrap/app. php.

When the terminate method is called on the middleware, Lumen will parse a new instance of the middleware from the service container. If you want to use the same middleware instance when processing the handle and terminate methods, use the singleton method when registering the middleware in the container.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.