设计模式五:管道模式

管道模式

  又称为Pipleline模式。将复杂的流程分解为多个子系统。将各个子系统按照逻辑次序排列有序的执行下去。类似于工厂的流水线。

  

<?php

class A
{
    public static function handle(){
        echo '请求验证'.PHP_EOL;
    }
}

class B
{
    public static function handle(){
        echo '数据过滤'.PHP_EOL;
    }
}

class C
{
    public static function handle(){
        echo '逻辑处理'.PHP_EOL;
    }
}

class D
{
    public function index(){
        echo '显示结果'.PHP_EOL;
    }
}

interface PiplineInterface{
    //请求需要执行的中间件
    public function pip($middlware);
    //请求的执行
    public function then();
}

/**
 * 管道类
 */
class Pipline implements PiplineInterface{
    
    protected $middlware = [];

    protected $request ;

    public function __construct($object , $method, $args=[])
    {
        $this->request['object'] = $object;
        $this->request['method'] = $method;
        $this->request['args'] = $args;
    }
    
    //中间件装载
    public function pip($middlware)
    {
        $this->middlware = $middlware;
        return $this;
    }

    //执行中间件
    public function then()
    {
        foreach($this->middlware as $value){
            //调用回调函数 $this->request
            call_user_func([$value,'handle']);
        }
        return $this;
    }

    public function send()
    {
        $method = $this->request['method'];
        return $this->request['object']->$method(...$this->request['args']);
    }
}

/**
 * 核心类 启动管道类
 */
class Kernel{

    protected $middlware = [];

    public function hanlde(PiplineInterface $pipline){
return $pipline->pip($this->middlware) ->then() ->send(); } } /** * 设置管道-中间件流程 */ class Http extends Kernel { protected $middlware = [ A::class, B::class, C::class ]; } $http = new Http(); $http->hanlde(new Pipline(new D(),'index'));

posted @ 2021-08-24 14:36  wish_yang  阅读(779)  评论(0编辑  收藏  举报