PHP code example of masroore / pipeline

1. Go to this page and download the library: Download masroore/pipeline library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

masroore / pipeline example snippets


interface PipelineStageInterface
{
    public function id(): string;

    public function process(PipelineContextInterface $context): void;
}

class TimesTwoStage implements PipelineStageInterface
{
    public function process(PipelineContextInterface $context): void
    {
        $val = (int) $context->getPayload();
        $val *= 2;
        $context->setPayload($val);
    }

    public function id(): string
    {
        return __CLASS__;
    }    
}

use Kaiju\Pipeline\PipelineBuilder;
use Kaiju\Pipeline\PipelineContextInterface;
use Kaiju\Pipeline\PipelineStageInterface;

class Payload implements PipelineContextInterface
{
    private int $value;
    private bool $halt;

    public function __construct(int $value)
    {
        $this->value = $value;
        $this->halt = false;
    }

    public function shouldHalt(): bool
    {
        return $this->halt;
    }

    public function setHalt(bool $halt): void
    {
        $this->halt = $halt;
    }

    public function getPayload(): int
    {
        return $this->value;
    }

    public function setPayload($payload): void
    {
        $this->value = (int) $payload;
    }
}

class TimesTwoStage implements PipelineStageInterface
{
    public function process(PipelineContextInterface $context): void
    {
        $val = (int) $context->getPayload();
        $val *= 2;
        $context->setPayload($val);
    }

    public function id(): string
    {
        return __CLASS__;
    }
}

class AddOneStage implements PipelineStageInterface
{
    public function process(PipelineContextInterface $context): void
    {
        $val = (int) $context->getPayload();
        $val++;
        $context->setPayload($val);
        $context->setHalt(true);
    }

    public function id(): string
    {
        return __CLASS__;
    }
}

$payload = new Payload(10);
$builder = (new PipelineBuilder())
    ->addStage(new TimesTwoStage())
    ->addStage(new AddOneStage());
$pipeline = $builder->build();
$pipeline($payload);
echo 'Value is: ' . $payload->getPayload();