lc5 / typed-collection
在 PHP 中创建严格类型集合
2.0.0
2021-12-09 19:37 UTC
Requires
- php: >=7.4.0
Requires (Dev)
- phpstan/phpstan: ^1.0
- phpunit/phpunit: ^9.5
- rector/rector: ^0.12.3
- symplify/easy-coding-standard: ^9.4
This package is not auto-updated.
Last update: 2024-09-28 07:50:27 UTC
README
在 PHP 中创建严格类型集合。
安装
$ composer require lc5/typed-collection
AbstractTypedCollection
一个抽象类,用于创建通过在 ArrayObject
周围实现类型检查包装的严格类型集合。集合中元素的类型是通过扩展 AbstractTypedCollection
并实现抽象方法 AbstractTypedCollection::getType
来定义的。它应该返回一个字符串作为类型,可以是任何类名或内部类型之一,这些类型可以通过内部 gettype() 函数识别("boolean", "integer", "double", "string", "array", "object", "resource", "NULL"
)。当尝试添加一个无效类型的元素时,将抛出 UnexpectedValueException
。
用法
use Lc5\TypedCollection\AbstractTypedCollection; use Lc5\TypedCollection\Exception\UnexpectedValueException; class stdClassCollection extends AbstractTypedCollection { public function getType(): string { return \stdClass::class; //can be any class or internal type } } $collection = new stdClassCollection([new \stdClass(), new \stdClass()]); $collection[] = new \stdClass(); try { $collection[] = 'invalid'; } catch (UnexpectedValueException $e) { echo $e->getMessage(); //Invalid value type: string. Only \stdClass is allowed. } try { $collection = new stdClassCollection(['invalid', new \stdClass()]); } catch (UnexpectedValueException $e) { echo $e->getMessage(); //Invalid value type: string. Only \stdClass is allowed. }
TypedCollection
基于 ArrayObject 的严格类型集合。集合中元素的类型通过构造函数参数定义,可以是任何类名或内部类型之一,这些类型可以通过内部 gettype() 函数识别("boolean", "integer", "double", "string", "array", "object", "resource", "NULL"
)。当尝试添加一个无效类型的元素时,将抛出 UnexpectedValueException
。
用法
use Lc5\TypedCollection\TypedArray; use Lc5\TypedCollection\Exception\UnexpectedValueException; $values = [new \stdClass(), new \stdClass()]; $typedCollection = new TypedCollection(\stdClass::class, $values); $typedCollection[] = new \stdClass(); try { $typedCollection[] = 'invalid'; } catch (UnexpectedValueException $e) { echo $e->getMessage(); //Invalid value type: string. Only \stdClass is allowed. }
行为与 AbstractTypedCollection
相同。