stephenfrank/

typedcollections

该软件包最新版本(0.1.0)没有可用的许可信息。

严格(近似)类型集合类

0.1.0 2014-03-26 16:31 UTC

This package is auto-updated.

Last update: 2024-09-18 21:08:44 UTC


README

stephenfrank/typedcollections: "0.1.x"

一组辅助类,用于强制数组集合中的类型安全性。

TypedCollection(基类)

基类是数组可访问的,并通过检查添加到集合中的每个项目与定义的类型是否匹配来强制类型严格性。

类型可以通过构造函数参数定义,或者根据添加的第一个项目自动定义。

$integerCollection = new TypedCollection([1, 2]);
$integerCollection[] = 'a'; // throws InvalidArgumentException

{类型}Collection

一些类内置了严格检查的类型

  • 布尔值 BoolCollection
  • 整数 IntegerCollection
  • 浮点数 FloatCollection
  • 字符串 StringCollection
  • 数组 ArrayCollection
  • 对象 ObjectCollection
$stringCollection = new StringCollection;
$stringCollection[] = 'foo';
$stringCollection[] = true; // throws InvalidArgumentException

ClassCollection

ClassCollection将通过使用get_class()检查添加到数组中的每个项目是否属于特定类。

$foosCollection = new ClassCollection([new Foo]);
// or new ClassCollection([new Foo], 'Foo');
$stringCollection[] = new StdClass; // throws InvalidArgumentException

InstanceCollection

InstanceCollection将使用instanceof检查每个项目,以便可以通过接口或继承类定义集合。

$foosCollection = new InstanceCollection([
	new ArrayObject,
	new ArrayIterator
], 'ArrayAccess'); // This is A-okay

这有什么意义?

有时在框架或库中公开公共API时,类型严格性很重要。这实际上减少了API消费者可能自我伤害的地方。

class NumberAdder
{
	public function sum(NumericCollection $numerics);
}

有时当使用第三方/遗留库时,您可能想对这些库返回的类型进行类型检查,并在它们没有返回干净数据时抛出异常。

$resources = new ClassCollection($thirdPartyThinger->getResources(), 'AcmeResource');
// Will explode if <Resource>[] is not returned

最后,InstanceCollection使创建自己的类型化集合变得非常容易。

class AcmeResourceCollection extends InstanceCollection
{
	protected $type = 'AcmeResource';
}