laravel 集合——迹忆客-ag捕鱼王app官网
简介
illuminate\support\collection
类为处理数组数据提供了流式、方便的封装。例如,查看下面的代码,我们使用辅助函数 collect
创建一个新的集合实例,为每一个元素运行 strtoupper 函数,然后移除所有空元素:
$collection = collect(['taylor', 'abigail', null])->map(function ($name) {
return strtoupper($name);
})->reject(function ($name) {
return empty($name);
});
正如你所看到的,collection 类允许你使用方法链对底层数组执行匹配和移除操作,通常,每个 collection 方法都会返回一个新的 collection 实例。
创建集合
正如上面所提到的,辅助函数 collect
返回一个新的 illuminate\support\collection
实例,所以说,创建集合是很简单的:
$collection = collect([1, 2, 3]);
注:默认情况下,eloquent 查询的结果总是返回 collection 实例。
扩展集合
集合是可扩展的,这意味着我们可以在运行时动态添加方法到 collection
类,例如,下面的代码给collection
类添加了 toupper
方法:
use illuminate\support\str;
collection::macro('toupper', function () {
return $this->map(function ($value) {
return str::upper($value);
});
});
$collection = collect(['first', 'second']);
$upper = $collection->toupper();
// ['first', 'second']
通常,我们需要在 service provider 中声明集合宏。
集合方法
本文档接下来的部分将会介绍 collection 类上每一个有效的方法,所有这些方法都可以以方法链的方式流式操作底层数组。此外,几乎每个方法返回一个新的 collection 实例,从而允许你在必要的时候保持原来的集合备份。
方法列表
- all
- average
- avg
- chunk
- collapse
- collect
- combine
- concat
- contains
- containsstrict
- count
- countby
- crossjoin
- dd
- diff
- diffassoc
- diffkeys
- dump
- duplicates
- duplicatesstrict
- each
- eachspread
- every
- except
- filter
- first
- firstwhere
- flatmap
- flatten
- flip
- forget
- forpage
- get
- groupby
- has
- implode
- intersect
- intersectbykeys
- isempty
- isnotempty
- join
- keyby
- keys
- last
- macro
- make
- map
- mapinto
- mapspread
- maptogroups
- mapwithkeys
- max
- median
- merge
- mergerecursive
- min
- mode
- nth
- only
- pad
- partition
- pipe
- pluck
- pop
- prepend
- pull
- push
- put
- random
- reduce
- reject
- replace
- replacerecursive
- reverse
- search
- shift
- shuffle
- skip
- skipuntil
- skipwhile
- slice
- some
- sort
- sortby
- sortbydesc
- sortdesc
- sortkeys
- sortkeysdesc
- splice
- split
- sum
- take
- takeuntil
- takewhile
- tap
- times
- toarray
- tojson
- transform
- union
- unique
- uniquestrict
- unless
- unlessempty
- unlessnotempty
- unwrap
- values
- when
- whenempty
- whennotempty
- where
- wherestrict
- wherebetween
- wherein
- whereinstrict
- whereinstanceof
- wherenotbetween
- wherenotin
- wherenotinstrict
- wherenotnull
- wherenull
- wrap
- zip
高阶消息传递
集合还支持“高阶消息传递”,也就是在集合上执行通用的功能,支持高阶消息传递的方法包括:average、avg、contains、each、every、filter、first、flatmap、groupby、keyby、map、max、min、partition、reject、some、sortby、sortbydesc、sum 和 unique。
每个高阶消息传递都可以在集合实例上以动态属性的方式访问,例如,我们使用 each 高阶消息传递来在集合的每个对象上调用一个方法:
$users = user::where('votes', '>', 500)->get();
$users->each->markasvip();
类似的,我们可以使用 sum 高阶消息传递来聚合用户集合的投票总数:
$users = user::where('group', 'development')->get();
return $users->sum->votes;
懒惰集合
简介
注:在具体了解懒集合之前,建议先花点时间熟悉下 php 生成器。
为了继续完善功能已经很强大的 collection 类,lazycollection 类使用了 php 的生成器,从而可以通过极低的内存处理极大的数据集。
例如,假设你的应用需要通过 laravel 提供的集合方法来解析并处理几个 gb 大小的日志文件,这个时候就可以使用懒集合(lazycollection),它不会一次性将整个文件读入内存,而是每次只读取文件的一小部分:
use app\logentry;
use illuminate\support\lazycollection;
lazycollection::make(function () {
$handle = fopen('log.txt', 'r');
while (($line = fgets($handle)) !== false) {
yield $line;
}
})->chunk(4)->map(function ($lines) {
return logentry::fromlines($lines);
})->each(function (logentry $logentry) {
// process the log entry...
});
或者,假设我们需要迭代产生 10000 个 eloquent 模型实例,使用传统的 laravel 集合,所有 10000 个 eloquent 模型实例必须一次性加载到内存中:
$users = app\user::all()->filter(function ($user) {
return $user->id > 500;
});
而现在,查询构建器的 cursor 方法会返回一个 lazycollection 实例,这样一来,我们仍然只需对数据库做一次查询,但是一次只会加载一个 eloquent 模型实例到内存。在这个例子中,filter 回调只有在迭代到每个独立用户时才会执行,从而大幅降低对内存的占用:
$users = app\user::cursor()->filter(function ($user) {
return $user->id > 500;
});
foreach ($users as $user) {
echo $user->id;
}
创建懒惰集合
要创建一个懒惰集合实例,需要传递一个 php 生成器函数到集合的 make 方法:
use illuminate\support\lazycollection;
lazycollection::make(function () {
$handle = fopen('log.txt', 'r');
while (($line = fgets($handle)) !== false) {
yield $line;
}
});
enumerable 接口
几乎所有的 collection 类方法都对 lazycollection 类有效,因为这两个类都实现了 illuminate\support\enumerable 接口,该接口中声明了如下方法::
- all
- average
- avg
- chunk
- collapse
- collect
- combine
- concat
- contains
- containsstrict
- count
- countby
- crossjoin
- dd
- diff
- diffassoc
- diffkeys
- dump
- duplicates
- duplicatesstrict
- each
- eachspread
- every
- except
- filter
- first
- firstwhere
- flatmap
- flatten
- flip
- forpage
- get
- groupby
- has
- implode
- intersect
- intersectbykeys
- isempty
- isnotempty
- join
- keyby
- keys
- last
- macro
- make
- map
- mapinto
- mapspread
- maptogroups
- mapwithkeys
- max
- median
- merge
- mergerecursive
- min
- mode
- nth
- only
- pad
- partition
- pipe
- pluck
- random
- reduce
- reject
- replace
- replacerecursive
- reverse
- search
- shuffle
- skip
- slice
- some
- sort
- sortby
- sortbydesc
- sortkeys
- sortkeysdesc
- split
- sum
- take
- tap
- times
- toarray
- tojson
- union
- unique
- uniquestrict
- unless
- unlessempty
- unlessnotempty
- unwrap
- values
- when
- whenempty
- whennotempty
- where
- wherestrict
- wherebetween
- wherein
- whereinstrict
- whereinstanceof
- wherenotbetween
- wherenotin
- wherenotinstrict
- wrap
- zip
注:改变集合的方法(例如 shift、pop、prepend 等)在 lazycollection 类中不可用。
懒惰集合方法
除了定义在 enumerable 契约中的方法,lazycollection 类还包含以下方法:
tapeach()
each 方法会为每个集合项立即调用给定回调,tapeach 方法则只有在这些集合项从列表中一个一个拉取出来时才会调用给定回调:
$lazycollection = lazycollection::times(inf)->tapeach(function ($value) {
dump($value);
});
// nothing has been dumped so far...
$array = $lazycollection->take(3)->all();
// 1
// 2
// 3
remember()
remember 方法返回一个新的懒集合,其中包含了所有已经枚举过的值,然后再次枚举的时候不会再从集合中获取它们:
$users = user::cursor()->remember();
// no query has been executed yet...
$users->take(5)->all();
// the query has been executed and the first 5 users have been hydrated from the database...
$users->take(20)->all();
// first 5 users come from the collection's cache... the rest are hydrated from the database.