markhj / collection
集合对象
Requires (Dev)
- phpunit/phpunit: 9.5
README
这个集合库最好理解为“升级版的面向对象数组”。
此包提供了编写更美观、易读代码的功能。
安装
您可以使用以下命令将此包安装到PHP项目中
composer require markhj/collection
您需要Composer 2。
示例
use Markhj\Collection\Collection; $collection = new Collection; $collection->push('John', 'Jane'); $collection->map(function($item) { return $item . ' Doe'; }); var_dump($collection->all()); // John Doe, Jane Doe
方法
public function push(...$objects): Collection; public function set($key, $object): Collection; public function add(Collection $collection): Collection; public function get($key); public function keyExists($key): bool; public function all(): array; public function count(?callable $filter = null): int; public function empty(): Collection; public function reverse(): Collection; public function keys(): Collection; public function toJson(): string; public function indexOf($item): ?int; public function remove(...$keys): Collection; public function first(); public function last(); public function clone(): Collection; public function append(Collection $collection): Collection; public function prepend(Collection $collection): Collection; public function crop(int $start, int $size): Collection; public function limit(int $limit): Collection; public function has($item): bool; public function hasAllOf(...$items): bool; public function hasAnyOf(...$items): bool; public function map(callable $handler): Collection; public function filter(callable $handler): Collection; public function forEach(callable $handler): Collection; public function retrieve(callable $filter): Collection; public function merge(Collection $target): Collection; public function mergePreserving(Collection $target): Collection; public function append(Collection $collection): Collection; public function prepend(Collection $collection): Collection; public function before($key, Collection $collection): Collection; public function after($key, Collection $collection): Collection; public function isAssociative(): bool; public function isGraceful(): bool;
下面有一些方法示例。
关联集合
关联集合提供了与非关联集合相同的所有功能,但使用类似于PHP关联数组的键/值对。
$collection = new AssociativeCollection; $collection->add('order', $order); $collection->add('customer', $customer); // ... $collection->get('customer'); // Returns the customer
语言特性
类型转换
当您将集合类型转换为字符串时,它将返回集合的JSON结构。
迭代
您可以在集合实例上使用foreach
运算符。
foreach ($collection as $key => $value) { // ... }
其他方法的使用示例
map
map
方法遍历集合的每个元素,并将处理程序返回的值分配给集合中的元素。
$collection = (new Collection) ->push(1, 2, 3) ->map(function($item, $key) { return $item * 2; }); // 2, 4, 6
forEach
forEach
方法在很多方面与map方法相似,但它不会将返回的值分配给集合中的元素。相反,您可以执行与集合本身不直接相关的操作。
$sum = 0; $collection = (new Collection) ->push(1, 2, 3) ->forEach(function($item, $key) use(&$sum) { return $sum += $item; }); // $sum is 6
sort
sort
方法根据定义的处理程序(可调用)对集合元素进行排序。
$collection = (new Collection) ->push(8, 2, 5) ->sort(function($a, $b) { return $a > $b; }); // 2, 5, 8
filter
filter
方法从集合中删除不需要的元素。
$collection = (new Collection) ->push(8, 2, 5) ->filter(function($a) { return $a != 2; }); // 8, 5
retrieve
retrieve
方法根据请求的元素创建一个新的(克隆的)集合。这允许您提取元素的一个筛选子集,而不会影响原始集合本身。
$evenNumbers = $collection->retrieve(function($a) { return $a % 2 == 0; });
has
has
方法如果在集合中找到目标项,则返回true。
$collection = (new Collection)->push(1, 2, 3); $collection->has(1); // true $collection->has(8); // false
has
方法也可以比较对象。
hasAnyOf
$collection = (new Collection)->push(1, 2, 3); $collection->hasAnyOf(2, 8); // true $collection->hasAnyOf(8, 11); // false
hasAllOf
$collection = (new Collection)->push(1, 2, 3); $collection->hasAllOf(2, 3); // true $collection->hasAllOf(2, 8); // false
merge
使用merge
方法,您可以将另一个集合合并到当前集合中。
$a = (new Collection)->push(1, 2, 3); $b = (new Collection)->push(1, 10, 20, 40); $a->merge($b); // 1, 10, 20, 40
您可以使用mergePreserving
来保护现有集合的值。
$a = (new Collection)->push(1, 2, 3); $b = (new Collection)->push(1, 10, 20, 40); $a->mergePreserving($b); // 1, 2, 3, 40
这些方法与append
和prepend
密切相关。
继承
您可以使用包中提供的“开箱即用”的集合对象,但在许多情况下,编写继承集合的自定义集合是有意义的。这允许您通过相关方法进行扩展。
验证
当您创建新的集合时,您可能希望将其限制为某些数据类型。为此,您可以重写方法
public function validate($item): bool
默认情况下,此方法始终返回true - 意味着它接受任何类型。
例如,您可以限制为字符串
public function validate($item): bool { return is_string($item); }
或特定类名
public function validate($item): bool { return get_class($item) == '...'; }
如果传递了错误的数据类型,将抛出InvalidItemTypeException
。
示例
例如,您可以为日期/时间对象创建一个集合,其中添加了检索最早和最新实例的方法。
class MyCustomDateCollection extends Collection { public function earliest() { // ... } public function latest() { // ... } }
另一个示例可能是支付方式集合,其中添加了与您的业务逻辑相关的方法。这可能是一个布尔方法,用于检查已过期的信用卡,一个获取所有信用卡的方法,或者一个检索默认支付方式的方法。
class PaymentMethodCollection extends Collection { public function hasExpiredCreditCard(): bool { // Pseudo/example code to find expired card return $this->count(function($paymentMethod) { return $paymentMethod->isExpired(); }) > 0; } public function getCreditCards(): Collection { return $this->retrieve(function($paymentMethod) { // Logic to determine of $paymentMethod is a credit card // or another type }); } public function getDefaultPaymentMethod(): ?PaymentMethod { // Find the default payment method } }
选项
优雅地处理缺失的键
当您正在操作继承自Collection对象的类时,可以将graceful
属性设置为true,以启用对尝试访问不存在的集合元素的优雅处理。在正常情况下,尝试访问不存在的元素将抛出KeyDoesNotExistException
异常。如果启用了优雅处理,并且尝试访问不存在的键,则返回NULL
。