• Closure


    加载中间件,注册回调事件。

    参考Larveal中间件加载方式
    具体代码如下:

    define("MALE",1);
    define("FEMALE",0);
    
    $request = new stdClass();
    $request->age = 9;
    $request->sex = MALE;
    $request->name = "小明";
    $request->info = "牛逼的人";
    
    
    //handle1,2,3,4是我要加入的注册事件,$request是原有请求
    function handle1(Closure $next){
        return function($request)use($next){
            if($request->age<10){
                echo "年龄小于10岁,不许坐车。",PHP_EOL;
            }
            return $next($request);
        };
    }
    function handle2(Closure $next){
        return function($request)use($next){
            return $next($request);
        };
    }
    function handle3(Closure $next){
        return function($request)use($next){
            return $next($request);
        };
    }
    function handle4(Closure $next){
        return function($request)use($next){
            return $next($request);
        };
    }
    
    function lastClosure(){
        return function($request){
            var_dump($request);
        };
    }
    
    //$p2 = call_user_func("handle1",lastClosure());
    //$p3 = call_user_func('handle2',$p2);
    //$p4= call_user_func('handle3',$p3);
    //$p5= call_user_func('handle4',$p4);
    //call_user_func($p5,$request);
    //die();
    
    $newPipe = new Pipe();
    Pipe::register("handle1");
    Pipe::register("handle2");
    Pipe::register("handle3");
    Pipe::register("handle4");
    $newPipe->run($request);
    
    class Pipe{
        private static $pipes;
        public function __construct(){
            self::$pipes = array();
        }
        public static function register($handle){
            self::$pipes[] = $handle;
        }
    
        //相当于 lastClosure()
        public function getFirstClosure(){
            return function($request){
                var_dump($request);
            };
        }
    
        public function getClosure(){
            return function($closure,$pipe){
                return function($request)use($closure,$pipe){
                    call_user_func(call_user_func($pipe,$closure),$request);
                };
            };
        }
    
        public function run($request){
            $firstClosure = $this->getFirstClosure();
            /**
             * 解释一下:
             * array_reduce(self::$pipes,$this->getClosure(),$firstClosure) 中间这个$this->getClosure()肯定是一个双重的closure.调用之后返回的还是一个Closure.
             */
            call_user_func(array_reduce(self::$pipes,$this->getClosure(),$firstClosure),$request);
        }
    
    }
    
  • 相关阅读:
    使用 C# .NET 在 ASP.NET 应用程序中实现基于窗体的身份验证
    高性能 Windows Socket 组件 HPSocket
    Linux下的C编程实战
    Scrum实践
    hadoop之NameNode,DataNode,Secondary NameNode
    代码抽象层次
    分布式统计的思考以及实现
    GCC起步
    学习 easyui 之一:easyloader 分析与使用
    从Prism中学习设计模式之MVVM 模式简述MVVM
  • 原文地址:https://www.cnblogs.com/canbefree/p/5242773.html
Copyright © 2020-2023  润新知