Created
March 10, 2024 10:09
-
-
Save diloabininyeri/fbd96f40fe5774dd6f1ba5cef437916f to your computer and use it in GitHub Desktop.
The an example of chain closure in php
This file contains 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
//dilo surucu | |
class Step | |
{ | |
/** | |
* @var Closure[] $steps | |
*/ | |
private array $steps; | |
public function add(Closure $step): void | |
{ | |
$this->steps[] = $step; | |
} | |
public function execute(mixed $data): mixed | |
{ | |
if (empty($this->steps)) { | |
return $data; | |
} | |
$next = function ($data) use (&$next) { | |
$nextClosure=next($this->steps) ?: static fn($d, Closure $next)=>$d; | |
return $nextClosure($data,$next); | |
}; | |
$startClosure = reset($this->steps); | |
return $startClosure($data, $next); | |
} | |
} | |
$step = new Step(); | |
$step->add(function (int $number, Closure $next) { | |
return $next($number + 1); | |
}); | |
$step->add(function (int $number, Closure $next) { | |
return $next($number / 4); | |
}); | |
$step->add(function (int $number,Closure $next) { | |
return $next($number*2); | |
}); | |
$step->add(function (int $number){ | |
return "the result of the step is $number"; | |
}); | |
echo $step->execute(7); //the result of the step is 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment