ts / collection
该软件包已被废弃,不再维护。未建议替代软件包。
简单的集合类,在需要的地方提供类型安全。
该软件包尚未发布版本,可用的信息不多。
README
简单的集合类,在需要的地方提供类型安全。
需求
所有组件都需要 PHP >= 5.5。
安装
使用 Composer 安装: composer require ts/collection:~3.0
使用默认集合
当向默认实现添加第一个项目时,设置预期值类型
use TS\Collection\Collection; // Create collection $coll = new Collection; // Collection accepts only stdClass objects afterwards $coll->add(new stdClass); // Throws an Exception $coll->add(new someClass); // Create collections from arrays $coll = Collection::fromArray([new stdClass, new stdClass]); // Throws an Exception $coll = Collection::fromArray([new stdClass, new someClass]);
自定义:扩展基本集合
当扩展基本集合类并期望某种类型的项目时,重写 expectsType
方法,该方法应返回集合应接受的类型的全限定类名
class MyCollection extends TS\Collection\Collection { protected function expectsType() { return 'stdClass'; } } $coll = new MyCollection; // Still works fine $coll->add(new stdClass); // Throws an Exception $coll->add(new someClass);
严格类型
集合类默认不区分类型的基类和子类。
要防止子类被放入集合中,将受保护的 $mode
属性设置为 TypeSafetyMode 类中定义的类型安全模式之一
use TS\Collection\Collection; use TS\Collection\TypeSafetyMode; class MyCollection extends Collection { protected $expectedType = 'stdClass'; protected $mode = TypeSafetyMode::STRICT; } // Note how this differs from the previous example: // someClass extends stdClass this time and would be a valid parameter in the default type safety mode class someClass extends stdClass {} $coll = new MyCollection(); // Fine $coll->add(new stdClass); // Throws an Exception $coll->add(new someClass);
合并
use TS\Collection\Collection; $john = (object) ['name' => 'John']; $jane = (object) ['name' => 'Jane']; $coll1 = new Collection; $coll1->add($john); $coll2 = new Collection; $coll2->add($jane); $merged = $coll1->mergeWith($coll2); $merged->contains($john); // true $merged->contains($jane); // true
过滤
Collection::filter()
期望一个以集合项目为参数的 PHP 可调用对象。
use TS\Collection\Collection; $john = (object) ['name' => 'John']; $james = (object) ['name' => 'James']; $coll = new Collection; $coll->add($john); $coll->add($james); $filtered = $coll->filter( function ($item) { if (strlen($item->name) <= 4) { return $item; } } ); $filtered->contains($john); // true $filtered->contains($james); // false
进一步操作
集合类继承自 Doctrine 的 ArrayCollection
,它提供了更多功能,如分区、映射、切片等,保持相同的接口,但增加了类型安全检查。