php设计模式之管道模式

对于管道模式来说,有3个对象:管道,载荷,过滤器。

我们的目的是在管道中对载荷进行一系列的处理。因为可以对过滤器进行动态的添加,
所以对载荷的处理可以变得更加灵活。但同时带来的问题是,在过滤器过多时,
我们很难把握整体的处理逻辑。而且在某一个过滤器对载荷处理后,因为载荷改变, 会造成下一个过滤器中的逻辑出错。

<?php

//过滤处理接口
interface StageInterface
{
    public function handle($payLoad);
}

//管道类
interface PipelineInterface
{
    public function __construct($payLoad);
 
    public function pipe(StageInterface $stage);
 
    public function process();
}
 
 


//过滤处理器-token检测
class JwtVerify implements StageInterface
{
    public function handle($payLoad)
    {
    	if(0){
    		return '权限检验失败';
		}
        return $payLoad + 1;
    }
}
//过滤处理器-日志写入
class AddLog StageInterface
{
    public function handle($payLoad)
    {
        return $payLoad + 2;
    }
}
 
//管道类 
class Pipeline implements PipelineInterface
{
    private $pipes;
    private $payLoad;
 
    public function __construct($payLoad)
    {
        $this->payLoad = $payLoad;
    }
 
    public function pipe(StageInterface $stage)
    {
        $this->pipes[] = $stage;
        return $this;
    }
 
    public function process()
    {
        foreach ($this->pipes as $eachPipe)
        {
            $this->payLoad = call_user_func([$eachPipe, 'handle'], $this->payLoad);
        }
 
        return $this->payLoad;
    }
}
 
 

//执行实例
class Action
{
    public function run()
    {
    	//最初的request
        $payLoad = 10;
 
		//需要处理的各种方法
        $jwtVerify = new JwtVerify();
        $addLog= new AddLog();
 
        $pipe = new Pipeline($payLoad);
 
 		//request挨个接受处理
        return $pipe->pipe($jwtVerify)->pipe($addLog)->process();
    }
}
 
$test = new Action();
$test->run();

在我们的示例中:管道类是Pipeline,载荷是在实例化Pipeline时传递的payLoad,过滤器是所有实现StageInterface的类。在web应用中,在服务器将请求分发给php的web入口文件到到达具体处理请求的文件的周期中,我们可以对request这个载荷的处理,可以应用管道模式(如thinkphp6的中间件)。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值