企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 创建core/PipleLine.php 中间件实现主要是靠 `PipeLine` ``` <?php namespace core; class PipeLine { // 所有要执行的类 protected $classes = []; // 类的方法名称 protected $handleMethod = 'handle'; // 因为容器的单例的,所以要创建一个新的 对象 public function create() { return clone $this; } // 没啥用 但是遵守原则而已 public function setHandleMethod($method) { $this->handleMethod = $method; return $this; } public function setClass($class) { $this->classes = $class; return $this; } // 传递闭包 运行管道 // 这个代码过于抽象 学习文章: https://segmentfault.com/a/1190000017792800 public function run(\Closure $initial) { return array_reduce( array_reverse($this->classes),function($res, $currClass){ return function ($request) use ($res,$currClass) { return (new $currClass)->{$this->handleMethod}($request,$res); }; },$initial); } } ``` ## 代码助你理解array_reduce ``` $datas = [ ['num' => 2, 'price' => 15], ['num' => 4, 'price' => 10], ]; ``` 现在要计算总价, `foreach`操作: ``` $sum = 0; foreach($datas as $data) $sum += $data['price'] * $data['num']; echo $sum; // 70 ``` 用 `array_reduce` ``` echo array_reduce($datas, function($sum = 0,$data){ return $sum += $data['num'] * $data['price']; }); // 70 ``` `array_reduce` 只是更简洁的写法而已,你大可用 `foreach` 来代替它。 (一般不会代替把,都喜欢简洁) ## 绑定pipeline ![](https://img.kancloud.cn/62/83/6283621cb580906cc7a98ae98c31244d_511x263.png) ## 编辑RouteCollection.php 编辑 `dispatch` 方法 ``` // 根据request执行路由 public function dispatch(RequestInterface $request) { $method = $request->getMethod(); $uri = $request->getUri(); $this->route_index = $method . $uri; $route = $this->getCurrRoute(); if(! $route) return 404; $middleware = $route['action']['middleware'] ?? []; $routerDispatch = $route['action']['uses']; return \App::getContainer()->get('pipeline')->create()->setClass( $middleware )->run($routerDispatch)($request); } } ``` ![](https://img.kancloud.cn/af/8b/af8b7eb5584c11b7b73130c2be6bb09f_449x145.png) ## 创建app/middleware/WebMiddleWare.php ``` <?php namespace App\middleware; class WebMiddleWare { public function handle($request,\Closure $next) { echo "web middleware"; return $next($request); } } ``` ### 编辑routes/web.php ![](https://img.kancloud.cn/0d/88/0d88bbcb006463112c36d7f7afb462ca_745x181.png) ![](https://img.kancloud.cn/f5/ee/f5ee28f4560c79372eb808c5a7c98efc_604x223.png) ### 在路由组添加中间件 ![](https://img.kancloud.cn/3b/86/3b86f365d21ccded7749bb6578971fcc_644x226.png) ![](https://img.kancloud.cn/60/18/601899d2def535574d91ce2d594c6748_864x262.png) ![](https://img.kancloud.cn/22/ee/22ee2bace19bf474bd3f9760553dcbb5_659x243.png)