pipeline依次传递给下个方法
2020-02-24 本文已影响0人
lifefruity
有一个字符串,依次需要多个机制来过滤,有点类似装饰器的感觉
<?php
interface Middleware{
public static function handle(Closure $content);
}
class FilterC implements Middleware{
public static function handle($content){
$new = str_replace('a', '', $content);
return $new;
}
}
class FilterB implements Middleware{
public static function handle($content){
$new = str_replace('b', '', $content);
return $new;
}
}
class FilterA implements Middleware{
public static function handle($content){
$new = str_replace('c', '', $content);
return $new;
}
}
function getSlice(){
return function ($content, $pipe){
return $pipe::handle($content);
};
}
function then(){
$pipes = ['FilterA', 'FilterB', 'FilterC'];
$pipes = array_reverse($pipes);
$filterContent = array_reduce($pipes, getSlice(), '12aa3456bb789cc1011');//把a b c都替换掉
echo $filterContent;// 输出"1234567891011"
}
then();