滑稽 的博客

Laravel5.4.10新增tap几何方法

翻译自:https://laravel-news.com/collection-tap

Laravel 5.4.10引入了一个新tap的集合方法,它允许你在特定点“挖掘”集合,并对结果做一些事情,而不影响主集合。


这个功能最好通过示例来描述,让我们假装你有以下数组:


$items = [

    ['name' => 'David Charleston', 'member' => 1, 'active' => 1],

    ['name' => 'Blain Charleston', 'member' => 0, 'active' => 0],

    ['name' => 'Megan Tarash', 'member' => 1, 'active' => 1],

    ['name' => 'Jonathan Phaedrus', 'member' => 1, 'active' => 1],

    ['name' => 'Paul Jackson', 'member' => 0, 'active' => 1]

];


现在我们将它转换为集合,过滤数据,并在两个不同的点进入它:


return collect($items)

    ->where('active', 1)

    ->tap(function($collection){

        return var_dump($collection->pluck('name'));

    })

    ->where('member', 1)

    ->tap(function($collection){

        return var_dump($collection->pluck('name'));

    });



一旦这个运行,它将输出一下的第一次tap结果:

David Charleston, Megan Tarash, Jonathan Phaedrus, Paul Jackson


然后第二次

David Charleston, Megan Tarash, Jonathan Phaedrus


tap 和 pipe 方法的对比


Laravel也提供了另一个类似的方法tap命名pipe,它们是相似的,因为它们可以在一个集合管道内执行。然而,它们有两个主要的区别:


tap允许您使用可用的数据做某事,但不会修改原始数据。pipe根据其返回值修改集合中的结果。例如:


return collect($items)

    ->where('active', 1)

    ->pipe(function ($collection) {

        return $collection->push(['name' => 'John Doe']);

    });


// 结果为: David Charleston, Megan Tarash, Jonathan Phaedrus, Paul Jackson, John Doe


评论
< >
更多文章来:https://alpha2016.github.io
< >
© 滑稽 的博客 | Powered by LOFTER