Home  >  Article  >  Backend Development  >  Content analysis of PHP intermediate keys

Content analysis of PHP intermediate keys

不言
不言Original
2018-08-04 11:58:071970browse

The content of this article is about the content analysis of PHP intermediate keys (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

PHP intermediate key: The so-called intermediate key is actually to execute some functions before or after executing routing. Before, you can check whether the API can be requested, whether it has permissions, etc., and the post-middleware can record some functions. Logs after execution, etc.

The temporarily thought of method is to encapsulate a method in the parent controller, execute beforeAction first when executing some functions, and then execute afterAction after executing the Action, so as to achieve a simple intermediate key.

After contacting laravel, I found that the intermediate key in laravel uses closure (Closure). A simple example is as follows:

$application = function ($names, $a){
    echo "this is a {$names} aaa {$a} application";    
    echo "<br />";
};// 前置中间键$auth = function ($handler){
    return function ($name, $as) use ($handler){
        echo "{$name} need {$as} a auth middleware";        
        echo "<br />";        
        return $handler;
    };
};
$stack = [];// 打包
function pack_middleware($handler, $stack){
    foreach (array_reverse($stack) as $key => $middleware) {        
    $handler = $middleware($handler);
    }    
    return $handler;
}
$stack[&#39;auth&#39;] = $auth;
$run = pack_middleware($application, $stack);
$run(&#39;Laravle&#39;, "aaaaa");

The final printed result is as follows

Laravle need aaaaa a auth middleware
this is a a aaa aa application

Among them array_reverse The functions are executed in sequence and finally return the result, for example:

$a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota");
print_r(array_reverse($a));

The final printed result is as follows: Array ( [c] => Toyota [b] => BMW [a] => Volvo )

Recommended related articles:

How to check whether a remote file exists in PHP (pure code)

How to create a soft connection in PHP (code )

The above is the detailed content of Content analysis of PHP intermediate keys. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn