模仿KOA,用php来写一个极简的开发框架

nodejs的koa能够说是很是受欢迎的,特别是其“洋葱模型”应该用过的人印象都比较深,下来就尝试用php来实现一个。php

注:本文是PHPec框架的最原始思路版本。PHPec是在此基础上完善编写出来的一个极简的轻量级开发框架,除了提供中间件调用模式外,同时提供了常见的自动路由功能,目前 已在github上发布了最第一版本。欢迎感兴趣的去了解和提出建议,也欢迎star. 地址:https://github.com/tim1020/PHPecnode

指望用法

先来看看我要怎么用“这个框架”?git

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方法添加中间件,支持闭包或外部文件。github

$ctx支持注入所需的各类参数,方便各中间件共用。闭包

完整代码

//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;
    }
}

没错,这就是所有的代码。app

代码讲解

use方法

use能够加入闭包或外部文件,且php5不支持use做为方法名,这里用__call来实现重载,当调用use时由__call来调用私有的_add方法。框架

_add对传进来的参数做判断,若是是字符串,表示外部加载,则去判断文件和处理函数是否存在和有效,而后将处理函数加到中间件队列。koa

这里面若是use()传递空参数,表示忽略后面的中间件。函数

run方法

添加完中间件后,执行$app -> run()方法运行,来看看是怎么执行的:ui

  1. 调用私有的_gen来生成一个生成器,该生成器能够迭代返回队列中的中间件处理函数。

  2. 调用next方法执行下一个中间件(这里即第一个入口)

    2.1 调用生成器的current方法得到当前的处理函数

    2.2 执行该函数(传递$this做为参数,即$ctx),并调用生成器的next方法后移到下一个处理函数

  3. 直到生成器没有返回时结束。

中间件中需调用$ctx-> next()将控制权交到下一个中间件,从而迭代完全部的中间件。

__get和__set方法

提供了__get和__set方法,是方便在中间件中使用$ctx直接设置和访问未经定义的值。如:

$ctx -> body = 'hello';
$ctx -> tplName = 'a.tpl';

That is all

相关文章
相关标签/搜索