<?php // 框架核心應用層 $application = function ($name) { echo "this is a {$name} application\n"; }; // 前置校驗中間件 $auth = function ($handler) { return function ($name) use ($handler) { echo "{$name} need a auth middleware\n"; return $handler($name); }; }; // 前置過濾中間件 $filter = function ($handler) { return function ($name) use ($handler) { echo "{$name} need a filter middleware\n"; return $handler($name); }; }; // 後置日誌中間件 $log = function ($handler) { return function ($name) use ($handler) { $return = $handler($name); echo "{$name} need a log middleware\n"; return $return; }; }; // 中間件棧 $stack = []; // 打包 function pack_middleware($handler, $stack) { foreach (array_reverse($stack) as $key => $middleware) { $handler = $middleware($handler); } return $handler; } // 註冊中間件 // 這裏用的都是全局中間件,實際應用時還能夠爲指定路由註冊局部中間件 $stack['log'] = $log; $stack['filter'] = $filter; $stack['auth'] = $auth; $run = pack_middleware($application, $stack); print_r($run); $run('Laravle');