编程

Laravel 新的集合方法 pipeThrough

1359 2022-01-12 15:33:45

Laravel v8.78.1 引入了一个新的集合方法 pipeThrough(), 允许开发者插入一个 pipe 回调函数数组,用来操作集合:

Recently merged into Laravel, you will soon be able to call collect()->pipeThrough($pipes) to run a collection through an array of callbacks, passing return values into following pipes ? pic.twitter.com/5m9fThcoaw

— Steve Bauman (@SteveTheBauman) January 5, 2022

用例:

$process = [
    // Iterate through the health checks and attempt,
    // filtering the collection by unsuccessful.
    fn ($checks) => $checks->filter(
        fn ($check) => ! $check->attempt()
    ),
 
    // Iterate through all the unsuccessful checks
    // notifying their users of each failed check.
    fn ($unsuccessful) => $unsuccessful->each(
        fn ($check) => $check->users()->each(
            fn ($user) => $user->notify(
                new HealthCheckFailed($check)
            )
        )
    )
];
 
collect(HealthChecks::all())->pipeThrough($process);

pipeThrough() 方法是一种灵活的方式,通过一系列回调方法和反射类来运行集合代码。但是,它的实现其实是简单的。这是版本发布时的集合类的 pipeThrough 方法:

public function pipeThrough($pipes)
{
    return static::make($pipes)->reduce(
        function ($carry, $pipe) {
            return $pipe($carry);
        },
        $this,
    );
}

集合类 Collection 中, 与此相似的是 pipe() 方法,此方法只接收一个 callable,返回闭包的执行结果。

$collection = collect([1, 2, 3]);
 
$piped = $collection->pipe(function ($collection) {
    return $collection->sum();
});