Skip to content

Instantly share code, notes, and snippets.

@missoxd
Created March 7, 2019 05:04
Show Gist options
  • Save missoxd/17d23e45302ea7a3bbfb6a9aaeabe830 to your computer and use it in GitHub Desktop.
Save missoxd/17d23e45302ea7a3bbfb6a9aaeabe830 to your computer and use it in GitHub Desktop.
Simple pipeline middleware like for closures
<?php
$pipeline = [];
$pipeline['first_pipe'] = function (array $params, callable $next) {
echo "first pipe\n";
$params['first_pipe_part_1'] = true;
print_r($params);
$params = $next($params);
echo "real last! >D\n";
$params['first_pipe_part_2'] = true;
print_r($params);
return $params;
};
$pipeline['second_pipe'] = function (array $params, callable $next) {
echo "second pipe\n";
$params['second_pipe'] = true;
print_r($params);
return $next($params);
};
$pipefy = function (callable $stack, $pipes = []) use ($pipeline) {
$stackOn = function ($stack, $next) {
return function (array $params) use ($next, $stack) {
return $next($params, $stack);
};
};
foreach (array_reverse($pipes) as $pipe) {
$stack = $stackOn($stack, $pipeline[$pipe]);
}
return $stack;
};
$main = function (array $params) {
echo "at last!!!! ouch, maybe not ...\n";
$params['last_pipe'] = true;
print_r($params);
return $params;
};
$boom = $pipefy($main, ['first_pipe', 'second_pipe']);
$boom(['normal_param' => true]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment