idimsh/collection

一个通用的对象/变量持有器和迭代器

dev-master 2020-08-30 11:25 UTC

This package is auto-updated.

Last update: 2024-09-29 05:28:04 UTC


README

Build Status Scrutinizer Code Quality Code Coverage Software License

Collection:一个通用的PHP对象/变量持有器和迭代器

一个库,用于在迭代器中存储变量,支持一些操作,如排序和交换元素。

需求

  • PHP >= 5.6

安装

$ composer require idimsh/collection

composer.json

"require": {
  "idimsh/collection": "dev-master"
}

使用

\Dimsh\Models\Collections\Collection 类旨在被你创建的 列表 实现扩展,扩展类将提供自动完成的类型提示,但这不是必须的。
例如

use Dimsh\Models\Collections;

/**
 * Class DefinitionsList
 *
 * @method \Definition offsetGet();
 * @method \Definition current()
 * @method \Definition last()
 * @method \Definition first()
 *
 */
class DefinitionsList extends Collection {
    /**
     * @param \Definition $value
     *
     * @throws \Exception
     */
    protected function preAdd($value) {
        if (! $value instanceof \Definition) {
            throw new \Exception("DefinitionsList can accept items of type Definition only");
        }
    }
}

$list = new \DefinitionsList;
$list[] = new \Definition;
$list['string-index'] = new \Definition;
$list->add(new \Definition);

// Looping
for ($list->rewind(); $list->valid(); $list->next()) {
    $definition = $list->current();
    $index = $list->key();
}

有用的方法

/**
 * @var \Dimsh\Models\Collections\Collection $list
 * @var \Dimsh\Models\Collections\Collection $another_list
 */
 
$list->first(); // Get the first item
$list->last(); // Get the last

$list->swap($offset1, $offset2); // swap items
$list->diffKey($another_list); // Get array diff by keys (offsets)
$list->intersectKey($another_list); // get array_intersect_key using offsets.

原因

为了找到一个方法来将对象存储在类似数组的对象中,以便集合可以通过引用传递,将对象存储在PHP数组中不会提供此功能。

许可证

MIT

替代方案

\SplObjectStorage 提供了一种存储对象的方式,此包为此对象集合添加了数组函数。