Home>Article>Backend Development> Content analysis of PHP intermediate keys
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 "
"; };// 前置中间键$auth = function ($handler){ return function ($name, $as) use ($handler){ echo "{$name} need {$as} a auth middleware"; echo "
"; return $handler; }; }; $stack = [];// 打包 function pack_middleware($handler, $stack){ foreach (array_reverse($stack) as $key => $middleware) { $handler = $middleware($handler); } return $handler; } $stack['auth'] = $auth; $run = pack_middleware($application, $stack); $run('Laravle', "aaaaa");
The final printed result is as follows
Laravle need aaaaa a auth middleware this is a a aaa aa application
Among themarray_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!