nodejs的koa能够说是很是受欢迎的,特别是其“洋葱模型”应该用过的人印象都比较深,下面就尝试用php来实现一个。php
注:本文是PHPec框架的最原始思路版本。PHPec是在此基础上完善编写出来的一个极简的轻量级开发框架,除了提供中间件调用模式外,同时提供了常见的自动路由功能,目前 已在github上发布了最第一版本。欢迎感兴趣的去了解和提出建议,也欢迎star. 地址: https://github.com/tim1020/PHPec
先来看看我要怎么用“这个框架”?node
require 'app.php'; $app = new App(); $app -> use(function($ctx){ $ctx -> body.= '>m1'; $ctx -> next(); $ctx -> body .= '>m1 end'; }); $app -> use('Middleware2'); $app -> run();
基本上跟koa相似,先new一个app对象,使用use方法添加中间件,支持闭包或外部文件。git
$ctx支持注入所需的各类参数,方便各中间件共用。github
//app.php class App{ private $m = array(); private $ctx = array(); function next(){ $f = $this -> c -> current(); if(!$f) return; $this -> c -> next(); $f($this); } function run(){ $this -> c = $this -> _gen(); $this -> next(); } private function _gen(){ foreach($this -> m as $v){ yield $v; } } private function _add($m){ if(!empty($this->m) && $this -> m[count($this->m) -1] === false) return; if(!$m){ $this -> m[] = false; }elseif(($m instanceof Closure)){ $this -> m[] = $m; }else{ $m = $this -> _load($m); if(!function_exists($m)){ throw new Exception('middleware error'); } else $this -> m[] = $m; } } //处理文件加载,返回执行函数(如须要,可加入命名空间处理) private function _load($m){ $f = './middleware/'.$m.".php"; if(!file_exists($f)) throw new Exception('middleware error'); require $f; return $m; } function __call($m,$v){ if('use' == $m){ $p = isset($v[0]) ? $v[0] : ''; $this -> _add($p); }else{ throw new Exception('method not exists'); } } function __set($k,$v){ $this -> ctx[$k] = $v; } function __get($k){ return isset($this -> ctx[$k]) ? $this -> ctx[$k] : NULL; } }
没错,这就是所有的代码。闭包
use能够加入闭包或外部文件,且php5不支持use做为方法名,这里用__call来实现重载,当调用use时由__call来调用私有的_add方法。app
_add对传进来的参数做判断,若是是字符串,表示外部加载,则去判断文件和处理函数是否存在和有效,而后将处理函数加到中间件队列。框架
这里面若是use()传递空参数,表示忽略后面的中间件。
添加完中间件后,执行$app -> run()方法运行,来看看是怎么执行的:koa
2.1 调用生成器的current方法得到当前的处理函数函数
2.2 执行该函数(传递$this做为参数,即$ctx),并调用生成器的next方法后移到下一个处理函数ui
中间件中需调用$ctx-> next()将控制权交到下一个中间件,从而迭代完全部的中间件。
提供了__get和__set方法,是方便在中间件中使用$ctx直接设置和访问未经定义的值。如:
$ctx -> body = 'hello'; $ctx -> tplName = 'a.tpl';