search
HomePHP FrameworkLaravelAnalysis of ideas for creating laravel middleware

There are many implementation principles for parsing laravel middleware on the Internet, but I wonder if there are readers who don’t understand when reading. How did the author think of using the array_reduce function?

Recommended: laravel tutorial

This article starts from my own perspective and simulates how I would implement this middleware function if I were the author, and how to find and Use the corresponding function.

What is laravel middleware

Laravel middleware provides a mechanism to interrupt the original program flow and process it through middleware without modifying the logic code. Some events, or extend some functions. For example, logging middleware can easily record request and response logs without changing the logic code.

Then let’s simplify the software execution process. Now there is a core class kernel, and the following is its laravel code

#捕获请求
$request = Illuminate\Http\Request::capture()
#处理请求
$response = $kernel->handle($request);

The function of the code is to capture a Request and return a Response. Here is the code segment that is subsequently distributed to the specific execution logic and returns the results.

So if you want to add a piece of logic before or after executing the $kernel->handle() method, how would you write it? It's roughly as follows:

$request = Illuminate\Http\Request::capture()
function midware(){
    before()#在之前执行的语句集合
    #####    
    $response = $kernel->handle($request);
    #####
    after()#在之后执行的语句集合
}

Obviously there is no problem with writing this way, but it has no scalability. You have to change this method to execute anything. It is impossible to encapsulate it into the core content of the framework. How to improve it

Define a middleware class to be executed called middleware. The class implements two methods, before() and after(), and the code is as follows.

#配置项中有一项配置中间件:
middleware = '';
$request = Illuminate\Http\Request::capture()
function midware(){
    middleware.before()
    #####    
    $response = $kernel->handle($request);
    #####
    middleware.after()
}

Does it solve the problem? It solves the problem of not having to change it. But what if we need multiple middlewares? The easiest thing to think of is: define a middleware array middleware_arr, each middleware class Both contain before and after methods. The code is as follows:

#配置项中有middleware_arr
middleware_arr=array();
$request = Illuminate\Http\Request::capture()
function midware(){
    foreach(middleware_arr as middleware){
       middleware.before()
    }
    #####    
    $response = $kernel->handle($request);
    #####
    foreach(middleware_arr as middleware){
        middleware.after()
    }
}

Although it is a bit old-fashioned, it does solve the problem. But there is still a problem with this, that is, how do we pass parameters to the middleware? Is it ok as follows:

$request = Illuminate\Http\Request::capture()
function midware(){
    foreach(middleware_arr as middleware){
       middleware.before($request)
    }
    #####    
    $response = $kernel->handle($request);
    #####
    foreach(middleware_arr as middleware){
        middleware.after($response)
    }
}

It seems to solve the problem, but if you analyze it carefully, you will find that every time it is given The middleware is all the original $request, which obviously doesn't work. Change it to the following:

$request = Illuminate\Http\Request::capture()
function midware(){
    foreach(middleware_arr as middleware){
       $request = middleware.before($request)
    }
    #####    
    $response = $kernel->handle($request);
    #####
    foreach(middleware_arr as middleware){
        $response = middleware.after($response)
    }
}

Another question is, assuming there are two middlewares A and B, what should be the execution order:

$request = Illuminate\Http\Request::capture()
$request = A.before($request);
$request = B.before($request);
$response = $kernel->handle($request);
$response = A.after();
$response = B.after();

Is this reasonable? It’s not easy to tell. Let’s assume that there is a middleware that records request and response logs. At this time, no matter where you put it, it cannot perfectly record the initial request and the final request. log. Is it necessary to write two classes in a similar situation, one to record the request and place it first in the middleware array, and one to process the response and place it at the last place in the array? It is better to reverse the middleware_arr array before executing the subsequent foreach, so that it meets the requirements:

$request = Illuminate\Http\Request::capture()
$request = A.before($request);
$request = B.before($request);
$response = $kernel->handle($request);
$response = B.after();
$response = A.after();

But I also began to wonder whether there is a better solution to this old-fashioned and inflexible solution. When observing this execution sequence, we found that it is a wrapper style (onion style). Can we find a more flexible and elegant solution to the next problem? Looking at the above structure, it always feels a bit familiar. It is very much like the function of A wraps the function of B, and the function of B includes the initial execution code. It is easy to call functions within a function, but each middleware here does not know the existence of the other, so the functions to be executed by other middleware must be passed to the upper level. Here, a closure function and a php function are used. array_reduce(),

array_reduce function definition: mixed array_reduce ( array $input , callable $function [, mixed $initial = NULL ] )

<?php
 function  rsum ( $v ,  $w )
{
     $v  +=  $w ;
    return  $v ;
}
function  rmul ( $v ,  $w )
{
     $v  *=  $w ;
    return  $v ;
}
 $a  = array( 1 ,  2 ,  3 ,  4 ,  5 );
 $x  = array();
 $b  =  array_reduce ( $a ,  "rsum" );
 $c  =  array_reduce ( $a ,  "rmul" ,  10 );
 ?>   
 #输出:
这将使 $b  的值为 15, $c  的值为 1200(= 10*1*2*3*4*5)

array_reduce() will act on the callback function iteratively to each cell in the input array, thereby reducing the array to a single value. We wrap multiple functions into one function that is finally called.

#我们先假设只有一个middleware,叫log来简化情况,这里的类应该是一个类全路径,我这里就简单的写一下,要不然太长了。
    $middleware_arr = [&#39;log&#39;];
#最终要执行的代码先封装成一个闭包,要不然没有办法传递到内层,如果用函数名传递函数的话,是没有办法传递参数的。
    $default = function() use($request){
        return $kernel->handle($request);
    }
    $callback = array_reduce($middleware_arr,function($stack,$pipe) {
        return function() use($stack,$pipe){
          return $pipe::handle($stack);
        };
    },$default);
    
    
# 这里 callback最终是 这样一个函数:
    function() use($default,$log){
          return $log::handle($default);
        };
        
#所以每一个中间件都需要有一个方法handle方法,方法中要对传输的函数进行运行,类似如下,这里我类名就不大写了
    class log implements Milldeware {
        public static function handle(Closure $func)
        {
            $func();
        }
    }
    
#这里不难看出可以加入中间件自身逻辑如下:
 class log implements Milldeware {
        public static function handle(Closure $func)
        {
            #这里可以运行逻辑块before()
            $func();
            #这里可以运行逻辑块after()
        }
    }

In this way, when executing the callback function, the execution sequence is as follows:

Run the log::haddle() method first,

execute the log::before() method

Run the default method and execute $kernel->handle($request)

Run the log::after() method

Then simulate multiple situations as follows:

    $middleware_arr = [&#39;csrf&#39;,&#39;log&#39;];
#最终要执行的代码先封装成一个闭包,要不然没有办法传递到内层,如果用函数名传递函数的话,是没有办法传递参数的。
    $default = function() use($request){
        return $kernel->handle($request);
    }
    $callback = array_reduce($middleware_arr,function($stack,$pipe) {
        return function() use($stack,$pipe){
          return $pipe::handle($stack);
        };
    },$default);
    
    
# 这里 callback最终是 执行这样:
    $log::handle(function() use($default,$csrf){
                    return $csrf::handle($default);
                });

The execution sequence is as follows:

1. First run the log::haddle (including csrf::handle closure function) method,

2. Execute log::before () method

3. Running the closure means running $csrf::handle($default)

4. Executing the csrf::before() method

5. Run the default method and execute $kernel->handle($request)

6. Execute the csrf::after() method

7. Run the log::after() method

Note that another problem here is that the results generated by the middleware are not transferred. The same purpose can be achieved by modifying the shared resources. It is not necessary to actually pass the value to the next middleware.

This is the end of this document. In fact, many of the joints were only figured out when I wrote this article. In particular, I have a deeper understanding of the use and understanding of closure functions. Closure functions can delay the use of resources. For example, statements that are not suitable for execution at the moment need to be passed to later. Closures can be used to encapsulate and pass them out. This is something that traditional functions cannot do. Arrived.

The above is the detailed content of Analysis of ideas for creating laravel middleware. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:cnblogs. If there is any infringement, please contact admin@php.cn delete
laravel单点登录方法详解laravel单点登录方法详解Jun 15, 2022 am 11:45 AM

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于单点登录的相关问题,单点登录是指在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统,下面一起来看一下,希望对大家有帮助。

一起来聊聊Laravel的生命周期一起来聊聊Laravel的生命周期Apr 25, 2022 pm 12:04 PM

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于Laravel的生命周期相关问题,Laravel 的生命周期从public\index.php开始,从public\index.php结束,希望对大家有帮助。

laravel中guard是什么laravel中guard是什么Jun 02, 2022 pm 05:54 PM

在laravel中,guard是一个用于用户认证的插件;guard的作用就是处理认证判断每一个请求,从数据库中读取数据和用户输入的对比,调用是否登录过或者允许通过的,并且Guard能非常灵活的构建一套自己的认证体系。

laravel中asset()方法怎么用laravel中asset()方法怎么用Jun 02, 2022 pm 04:55 PM

laravel中asset()方法的用法:1、用于引入静态文件,语法为“src="{{asset(‘需要引入的文件路径’)}}"”;2、用于给当前请求的scheme前端资源生成一个url,语法为“$url = asset('前端资源')”。

实例详解laravel使用中间件记录用户请求日志实例详解laravel使用中间件记录用户请求日志Apr 26, 2022 am 11:53 AM

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于使用中间件记录用户请求日志的相关问题,包括了创建中间件、注册中间件、记录用户访问等等内容,下面一起来看一下,希望对大家有帮助。

laravel中间件基础详解laravel中间件基础详解May 18, 2022 am 11:46 AM

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于中间件的相关问题,包括了什么是中间件、自定义中间件等等,中间件为过滤进入应用的 HTTP 请求提供了一套便利的机制,下面一起来看一下,希望对大家有帮助。

laravel的fill方法怎么用laravel的fill方法怎么用Jun 06, 2022 pm 03:33 PM

在laravel中,fill方法是一个给Eloquent实例赋值属性的方法,该方法可以理解为用于过滤前端传输过来的与模型中对应的多余字段;当调用该方法时,会先去检测当前Model的状态,根据fillable数组的设置,Model会处于不同的状态。

laravel路由文件在哪个目录里laravel路由文件在哪个目录里Apr 28, 2022 pm 01:07 PM

laravel路由文件在“routes”目录里。Laravel中所有的路由文件定义在routes目录下,它里面的内容会自动被框架加载;该目录下默认有四个路由文件用于给不同的入口使用:web.php、api.php、console.php等。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)