comquer / collection
此包最新版本(dev-master)没有可用的许可信息。
dev-master
2020-10-14 12:34 UTC
Requires (Dev)
- phpunit/phpunit: ^7.3
This package is auto-updated.
Last update: 2024-09-14 20:58:21 UTC
README
一个允许您创建类型化和/或唯一元素集合的库。为了使用它,只需让您的集合类继承自抽象的 Collection
类并在构造函数中设置它。
安装
最低要求的 PHP 版本是 7.4
composer require comquer/collection
示例
这是一个 UserCollection
的示例 - 一个元素集合,其中每个元素都必须是 User
的实例。此外,集合中的每个 User
必须有一个唯一的 id。
class UserCollection extends Collection { public function __construct(array $users = []) { parent::__construct( $users, // Set up typing - every element must be an instance of User Type::object(User::class), // Set up a unique index - user id new UniqueIndex(function (User $user) { return $user->getId(); }) ); } }
在这个示例中,我们有一个地址数组集合,其中唯一的索引是整个地址(所有字段连接在一起)。
class AddressCollection extends Collection { public function __construct(array $addresses = []) { parent::__construct( $addresses, // Set up typing - every element must be an array Type::array(), // Set up a unique index - all the fields new UniqueIndex(function (array $address) { return $address['postCode'] . $address['street'] . $address['homeNumber']; }) ); } }
Collection
还支持原始类型,如 int
或 string
。前往 测试 部分以检查更多用例。
文档
当然,Collection
做任何集合都会做的事情 - 您可以计数它,遍历它,添加和删除元素。如果集合设置了唯一索引,您还可以通过该索引从集合中获取元素。
Collection::add($element): self; Collection::addMany(self $collection): void; Collection::filter(callable $filter): self; Collection::remove($element): self; Collection::get($uniqueIndex): self; Collection::count(): int; Collection::getElements(): array; Collection::isTyped(): bool; Collection::hasUniqueIndex(): bool; Collection::rewind(); Collection::current(); Collection::key(); Collection::next(); Collection::valid(); Collection::isEmpty(): bool;