簡易版管道模式

lxdong12發表於2020-01-20
<?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 協議》,轉載必須註明作者和本文連結

相關文章