zoukankan      html  css  js  c++  java
  • 中间件实现原理

    ThinkPHP5.1x的中间件,其核心还是闭包函数的应用,来实现“责任链”模式:

    模拟代码:

    复制代码
    <?php
    
    //模拟的控制器
    class Controller {
        public function index($request) {
            echo '控制器方法体',$request,'<br>';
        }
    }
    
    //中间件
    class Before1 {
        public function handle($request, Closure $next) {
            echo 'before1<br>';  //业务逻辑,注意前置与后置中间件业务逻辑代码的位置
            return $next($request);
        }
    
    }
    //中间件
    class Before2 {
        public function handle($request, Closure $next) {
            echo 'before2<br>';
            return $next($request);
        }
    }
    //中间件
    class After1 {
        public function handle($request, Closure $next) {
            $response = $next($request);
            echo 'after1<br>'; //业务逻辑,注意前置与后置中间件业务逻辑代码的位置
            return $response;
        }
    }
    //中间件
    class After2 {
        public function handle($request, Closure $next) {
            $response = $next($request);
            echo 'after2<br>';
            return $response;
        }
    }
    
    class Middleware {
    
        public static $queue;  //中间件队列
        public static function init() {        
            //模拟的中间件,数量任意添加
            self::$queue[] = [[After1::class,  'handle'], null];
            self::$queue[] = [[After2::class,  'handle'], null];
            self::$queue[] = [[Before1::class, 'handle'], null];
            self::$queue[] = [[Before2::class, 'handle'], null];
             //模拟的控制器
            self::$queue[] = [[Controller::class,  'index'], null];
        }
        
        //调用中间件
        public static function dispatch($request) {
            call_user_func(self::resolve(), $request);
        }
        
        //返回闭包函数
        public static function resolve(){
            return function($request){
                $middleware = array_shift(self::$queue);
                if ($middleware != null) {
                    list($call, $param) = $middleware;
                    call_user_func_array($call, [$request, self::resolve()]);  //执行中间件
                }
            };
        }
    }
    
    $request = "模拟的request对象";
    Middleware::init();
    Middleware::dispatch($request);
  • 相关阅读:
    [WPF]Win10便签软件
    [WPF]使用Fody提高效率
    [WPF]限制程序单例运行
    [WPF]创建系统栏小图标
    Run Performance Testing Which Was Distributed To Multiple Test Agents
    FxZ,C#开发职位面试测试题(30分钟内必须完成)
    BYS推荐MS前端PhoneCall面试问题整理-2
    BYS推荐MS前端PhoneCall面试问题整理-1
    LxNx前端F2F面试问题整理
    复杂DIV交错布局
  • 原文地址:https://www.cnblogs.com/liliuguang/p/10856692.html
Copyright © 2011-2022 走看看