Skip to content

Instantly share code, notes, and snippets.

@oplanre
Created June 13, 2024 22:17
Show Gist options
  • Save oplanre/2a386cbce85c69e46f45aa6c7eda8f74 to your computer and use it in GitHub Desktop.
Save oplanre/2a386cbce85c69e46f45aa6c7eda8f74 to your computer and use it in GitHub Desktop.
Simple pipeline implementation in php as a class or function
<?php
class Pipeline {
public function __construct(
private mixed $data
) {}
public function pipe(callable ...$callbacks): static {
foreach ($callbacks as $callback) {
$this->data = $callback($this->data);
}
return $this;
}
public function get(): mixed {
return $this->data;
}
}
//or
function pipe(mixed $data, callable ...$callbacks): mixed {
foreach ($callbacks as $callback) {
$data = $callback($data);
}
return $data;
}
//Example usage
$pipeline = new Pipeline(5);
echo $pipeline->pipe(
fn($x) => $x * 4,
fn($x) => $x + 10,
fn($x) => $x / 2,
)->get();
// or
echo pipe(5,
fn($x) => $x * 4,
fn($x) => $x + 10,
fn($x) => $x / 2
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment