cocur / collection
Requires (Dev)
- mockery/mockery: ~0.9
- phpunit/phpunit: ~4.5
This package is auto-updated.
Last update: 2024-09-20 09:28:29 UTC
README
数组很棒,但有时项目需要知道它们所属的东西。这时你需要一个
Collection
。
由欧洲维也纳的 Florian Eckerstorfer (Twitter) 开发。
安装
$ composer require cocur/collection
用法
Collection 最重要的部分是其接口。它们使您的集合与其他库可互操作。然而,此库还包含可立即使用的实现。
接口
实现
CollectionInterface
Cocur\Collection\CollectionInterface
定义了集合的基本方法,并扩展了 IteratorAggregate
和 Countable
。
Cocur\Collection\CollectionInterface add(ItemInterface $item)
调用 add()
时,集合应调用项目的 setCollection()
方法并将自己设置为它的集合。
Iterator getIterator()
应返回一个迭代器来遍历集合中的项目。
int count()
应返回集合中项目的数量。
ItemInterface
Cocur\Collection\ItemInterface
定义了两个方法: setCollection()
和 getCollection()
。
ItemInterface setCollection(CollectionInterface $collection)
应在项目中存储对集合的引用。
CollectionInterface|null getCollection()
应返回对集合的引用或 null
,如果项目没有集合。
Collection
Cocur\Collection\Collection
实现 Cocur\Collection\CollectionInterface
并使用一个简单的数组来跟踪其项目。
AbstractItem
Cocur\Collection\AbstractItem
实现 Cocur\Collection\ItemInterface
中的方法。它简单地设置和获取集合,如果你不需要在项目上设置和获取集合的特定逻辑,它很棒。
AbstractItem
如其名所示是一个抽象类,你需要扩展它。
Item
Cocur\Collection\Item
扩展 Cocur\Collection\AbstractItem
并在 setCollection()
和 getCollection()
方法的基础上还实现了 setValue()
和 getValue()
来设置和获取任意值。你可以在标量值或不受你控制且未实现 ItemInterface
的对象周围包装 Item
。
Item setValue(mixed $value) mixed getValue()
此外,Cocur\Collection\Item
有一个名为 ::create()
的工厂方法
Item create(mixed $value = null)
ArrayItem
虽然 Item
存储单个值,但 Cocur\Collection\ArrayItem
旨在存储数组。它实现了设置、获取和从项目中删除元素的方法,以及检查它们的存在性。此外,toArray()
方法返回底层数组。
ArrayItem set(mixed $key, mixed $value) bool has(mixed $key) mixed get(mixed $key[, mixed $defaultValue]) ArrayItem remove(mixed $key() array toArray()
如果具有给定键的元素不存在,则 get()
和 remove()
方法抛出 OutOfBoundsException
。然而,除了抛出异常外,如果提供了第二个参数,则 get()
也可以返回默认值。
你可以使用静态 ::createFromArray()
方法创建新实例
ArrayItem createFromArray(array $data = [])
由于 ArrayItem
实现 ArrayAccess
、IteratorAggregate
和 Countable
,因此你可以在大多数情况下像使用数组一样使用它。
$item = ArrayItem::createFromArray(['foo' => 'bar'); $item['qoo'] = 'qoz'; echo count($item); // -> 2 if (isset($item['qoo'])) { echo $item['qoo']; // -> "qoz" } foreach ($item as $key => $value) { echo "$key: $value, "; } // -> "foo: bar, qoo: qoz, "
变更日志
版本 0.1.1 (2015年5月18日)
- 为
ArrayItem::get()
添加了默认值选项
版本 0.1 (2015年4月28日)
- 首次发布
许可证
MIT 许可证适用于 cocur/collection。有关完整的版权和许可信息,请查看与此源代码一起分发的 LICENSE 文件。