Content analysis of PHP intermediate keys

不言
Release: 2023-04-03 15:38:01
Original
1926 people have browsed it

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");
Copy after login

The final printed result is as follows

Laravle need aaaaa a auth middleware this is a a aaa aa application
Copy after login

Among themarray_reverseThe 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));
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!