简易版管道模式

<?php
interface PipelineInterface
{
    public function send($traveler);
    public function through($stops);
    public function via($method);
    public function then();
}

interface StageInterface
{
    public function handle($payload);
}

class StageOne implements StageInterface
{
    public function handle($payload) 
    {
        echo $payload . ' am really an ';
    }
} 

class StageTwo implements StageInterface
{
    public function handle($payload) {
        echo 'awesome man';
    }
} 

class Pipe implements PipelineInterface
{

    protected $passable;
    protected $pipes = [];
    protected $via = 'handle';

    public function send($passable)
    {
        $this->passable = $passable;

        return $this;
    }

    public function through($pipes)
    {
        $this->pipes = is_array($pipes) ? $pipes : func_get_args();

        return $this;
    }

    public function via($method)
    {
        $this->via = $method;

        return $this;
    }

    public function then()
    {
        foreach ($this->pipes as $pipe) {
            // 返回处理后的结果
            $this->passable = call_user_func([$pipe, $this->via], $this->passable);
        }
    }
}
$payload = 'I';
$pipe = new Pipe();

// 输出:I am really an awesome man
$pipe->through([(new StageOne), (new StageTwo)])->send($payload)->then();
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!