Created
June 13, 2024 22:17
-
-
Save oplanre/2a386cbce85c69e46f45aa6c7eda8f74 to your computer and use it in GitHub Desktop.
Simple pipeline implementation in php as a class or function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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