linkorb / collection
超级强大的集合
v1.0.0
2017-08-05 08:56 UTC
This package is auto-updated.
Last update: 2024-08-29 04:41:11 UTC
README
这个库实现了一些有用的集合类和接口。
TypedArray
这个类的行为与数组完全相同,但只允许指定类型的项
$monkeys = new \Collection\TypedArray(Monkey::class); $monkeys->add(new Monkey('Bubbles')); // OK $monkeys[] = new Monkey('King Kong'); // OK $monkeys->add(new Snake('Kaa')); // throws CollectionException // You can iterate over the collection foreach ($monkeys as $monkey) { echo $monkey->getName(); }
向集合中添加项
您可以使用常规数组方式添加项
$monkeys[] = new Monkey('King Kong');
或使用 add()
方法
$monkeys->add(new Monkey('King Kong'));
可识别接口
Identifiable
类强制类实现 identifier()
方法。该方法应返回一个键,使类的此实例唯一。这可能是一个ID、一个键、一个名称或一个电子邮件地址,只要它能唯一标识项即可。
class Monkey implements \Collection\Identifiable { protected $name; public function __construct($name) { $this->name = $name; } public function identifier() { return $this->name; } }
当将此类的实例添加到集合中时,标识符将自动用作键
$monkeys = new \Collection\TypedArray(Monkey::class); $m1 = new Monkey('George'); $m2 = new Monkey('Koko'); $monkeys[] = $m1; // array contains 1 item $monkeys[] = $m2; // array contains 2 item $monkeys[] = $m2; // array still contains 2 items! $monkeys->add($m2); // array still contains 2 items! $monkeys->hasKey('George')); // returns true $monkeys->hasKey('King Kong')); // returns false isset($monkeys['George']); // returns true
在类中使用集合
class Zoo { protected $monkeys; public function __construct() { $this->monkeys = new Collection\TypedArray(Monkey::class); } public function getMonkeys() { return $this->monkeys; } } $zoo = new Zoo(); $zoo->getMonkeys()->add(new Monkey('Koko'); foreach ($zoo->getMonkeys() as $monkey() { }