PHP code example of georgeff / pipeline

1. Go to this page and download the library: Download georgeff/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/ */

    

georgeff / pipeline example snippets


use Georgeff\Pipeline\Stage;
use Georgeff\Pipeline\Pipeline;

$pipeline = (new Pipeline())
    ->pipe(Stage::from(fn($payload) => $payload * 2))
    ->pipe(Stage::from(fn($payload) => $payload + 1));

$result = $pipeline->process(5); // 11

use Georgeff\Pipeline\StageInterface;

final class MultiplyStage implements StageInterface
{
    public function __construct(private readonly int $factor)
    {
    }

    public function __invoke(mixed $payload): mixed
    {
        return $payload * $this->factor;
    }
}

$pipeline = (new Pipeline())
    ->pipe(new MultiplyStage(2))
    ->pipe(new MultiplyStage(3));

$result = $pipeline->process(5); // 30

$pipeline = (new Pipeline())
    ->pipe(Stage::from(fn($payload) => $payload * 2));

$base = (new Pipeline())
    ->pipe(new ValidateOrder());

$adminPipeline = $base->pipe(new AdminCheck());
$userPipeline = $base->pipe(new UserCheck());

// $base remains unchanged

use Georgeff\Pipeline\PipelineFactory;

$pipeline = PipelineFactory::build(
    new ValidateOrder(),
    new ProcessPayment(),
    new SendConfirmation()
);

use Georgeff\Pipeline\ConditionalStage;

$pipeline = (new Pipeline())
    ->pipe(new ConditionalStage(
        fn($order) => $order->isPriority(),
        new PriorityProcessing(),
        new StandardProcessing()
    ));

$pipeline = (new Pipeline())
    ->pipe(new ConditionalStage(
        fn($order) => $order->needsReview(),
        new FlagForReview()
    ));

use Georgeff\Pipeline\SwitchStage;

$pipeline = (new Pipeline())
    ->pipe(new SwitchStage(
        fn($order) => $order->getType(),
        [
            'digital' => new ProcessDigitalOrder(),
            'physical' => new ProcessPhysicalOrder(),
            'subscription' => new ProcessSubscription(),
        ],
        new ProcessUnknownOrder() // optional default
    ));

use Georgeff\Pipeline\StageInterface;
use Georgeff\Pipeline\StoppableInterface;

final class ValidationStage implements StageInterface, StoppableInterface
{
    public function __invoke(mixed $payload): mixed
    {
        $payload->validate();
        return $payload;
    }

    public function shouldStop(mixed $payload): bool
    {
        return $payload->hasErrors();
    }
}

$validation = (new Pipeline())
    ->pipe(new ValidateFields())
    ->pipe(new ValidateBusinessRules());

$processing = (new Pipeline())
    ->pipe(new CalculateTotals())
    ->pipe(new ApplyDiscounts());

$pipeline = (new Pipeline())
    ->pipe($validation)
    ->pipe($processing)
    ->pipe(new SaveOrder());