函数组合和集合管道模式 - Collection Pipeline
定义
集合管道是将一些计算转化为一系列操作,每个操作的输出结果都是一个集合,同时该结果作为下一个操作的输入。在函数编程中,通常会通过一系列更小的模块化函数或运算来对复杂运算进行排序,这种方式被称为函数组合。
结构中包含的角色
Collection 集合对象
最小可表达代码 - Laravel的Collection类
class Collection | |
{ | |
protected $items = []; | |
public function __construct($items = []) | |
{ | |
$this->items = $this->getArrayableItems($items); | |
} | |
public function all() | |
{ | |
return $this->items; | |
} | |
public function merge($items) | |
{ | |
return new static(array_merge($this->items, $this->getArrayableItems($items))); | |
} | |
public function intersect($items) | |
{ | |
return new static(array_intersect($this->items, $this->getArrayableItems($items))); | |
} | |
public function diff($items) | |
{ | |
return new static(array_diff($this->items, $this->getArrayableItems($items))); | |
} | |
protected function getArrayableItems($items) | |
{ | |
if (is_array($items)) { | |
return $items; | |
} elseif ($items instanceof self) { | |
return $items->all(); | |
} | |
return (array) $items; | |
} | |
} | |
$data = (new Collection([1,2,3])) | |
->merge([4,5]) | |
->diff([5,6,7]) | |
->intersect([3,4,5,6]) | |
->all(); | |
var_dump($data); |
何时使用
- 当要执行一系列操作时。
- 在代码中使用大量语句时。
- 在代码中使用大量循环时。
实际应用场景
- Laravel的集合