krak/coll

PHP 集合库

v0.1 2016-04-25 20:38 UTC

This package is auto-updated.

Last update: 2024-09-18 17:58:12 UTC


README

集合库是生成 PHP 对象集合的另一种尝试。

目前,这里唯一的集合是 Set,因为 PHP 实际上缺少这样的集合。

安装

compose require krak/coll

用法

Set

集合表示一组唯一值。

Set 类型有两种接口:`ConstSet` 和 `Set`。

常量集合只允许读取访问,而集合允许读写访问。

// const methods
public function get($value);
public function has($value);
public function count();
public function getIterator();

// non-const methods
public function add($value);
public function remove($value);
<?php

use Krak\Coll\Set;

$s1 = new Set\ArraySet();
// or
$s1 = Set\ArraySet::create([1,2,3]);

$s1->add(4);
$s2 = set\union($s1, Set\ArraySet::create([3,4]));

set\is_subset($s2, $s1); // returns true because s1 is a subset of s2

// if you need to store object values

// internally uses SplObjectStorage
$oset = new Set\ObjectSet();
$oset->add(new stdClass());

// if you need to store values that work as array keys
$hset = new Set\HashSet();
$hset->add(['a' => 1]);

// if you need to store any of those types of values
$aset = new Set\AnySet();
set\fill($aset, [1, [1], new stdClass()]);

每个集合都可作为可迭代和可计数对象使用

<?php

count($s1); // returns the count
foreach ($s1 as $val) {
    // iterate over the set values
}

用于类型提示,请使用 `Set` 或 `ConstSet`

<?php

use Krak\Coll\Set;

function operate_on_mutable(Set\Set $s1) {
    // ...
}

function operate_on_immutable(Set\ConstSet $s1) {
    // ...
}

如前所述,我们确实有多个集合操作函数。

// similar to union, but can work with different typed set (AnySet and ArraySet)
function join(ConstSet $s1, ConstSet $s2, $factory = null);
// s1 + s2
function union(ConstSet $s1, ConstSet $s2);
// s1 * s2
function intersect(ConstSet $s1, ConstSet $s2);
// s1 - s2
function difference(ConstSet $s1, ConstSet $s2);
// compares to sets returns true if s2 is subset of s1
function is_subset(ConstSet $s1, ConstSet $s2);
// compares to sets returns true on equal
function equals(ConstSet $s1, ConstSet $s2);
// fills a set with values and returns it
function fill(Set $s1, $values);

除了功能方法之外,还有一个类似这样的面向对象接口

<?php
$s1->union($s2)
    ->intersect($s3)
    ->difference($s4)
    ->equals($s5);