jakubgiminski / collection
该包最新版本(2.0.0)没有可用的许可信息。
2.0.0
2020-07-10 10:28 UTC
Requires (Dev)
- phpunit/phpunit: ^7.3
This package is auto-updated.
Last update: 2024-09-10 20:04:46 UTC
README
一个允许你创建类型化和/或唯一元素集合的库。为了使用它,只需让您的集合类扩展抽象类 Collection 并在构造函数中设置它。
安装
最低要求的php版本是 7.4
composer require jakubgiminski/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;