krlove / collections
PHP 的严格类型数据结构
1.0.0
2022-08-14 20:53 UTC
Requires
- php: >=7.4
Requires (Dev)
- phpunit/phpunit: ^9.5
- vimeo/psalm: ^4.26
README
严格类型的 PHP 数据结构。
安装
composer require krlove/collections
序列
序列是任何类型的变量的有序集合。
$sequence = Sequence::of('string'); $sequence->push('Gandalf'); $sequence->push('Bilbo'); $sequence->push('Frodo'); $sequence->remove(1); foreach ($sequence as $index => $value) { echo $index . ': ' . $value . PHP_EOL; }
0: Gandalf
1: Frodo
映射
映射包含键值对,每个键都是唯一的。
$map = Map::of('string', 'array'); $map->set('fruits', ['apple', 'banana', 'pear']); $map->set('vegetables', ['tomato', 'potato', 'onion']); $map->set('berries', ['strawberry', 'blueberry', 'raspberry']); $map->remove('vegetables'); $map->set('berries', ['bilberry']); foreach ($map as $key => $value) { echo $key . ': ' . var_export($value, true) . PHP_EOL; }
fruits: array (
0 => 'apple',
1 => 'banana',
2 => 'pear',
)
berries: array (
0 => 'bilberry',
)
集合
集合是任何类型唯一变量的集合。
$set = Set::of('string'); $set->add('Gandalf'); $set->add('Bilbo'); $set->add('Bilbo'); echo var_export($set->toArray(), true) . PHP_EOL;
array (
0 => 'Gandalf',
1 => 'Bilbo',
)
类型
所有集合都是严格类型的。
$sequence = Sequence::of('int'); $sequence->push('Gandalf');
PHP Fatal error: Uncaught Krlove\Collection\Exception\TypeException: Variable must be of type int, string given
支持的类型有
- null
- bool
- int
- float
- string
- array
- iterable
- callable
- resource
- object
- class (特定类或接口的对象)
- mixed (允许任何类型)
可空
类型可以是可空的。
$sequence = Sequence::of('?string'); $sequence->push(null);
可冻结
在集合“冻结”后,它变为只读,不允许对其进行更改。一旦冻结,就无法“解冻”集合,但可以复制它。
$sequence = Sequence::of('string'); $sequence->push('Gandalf'); $sequence->freeze(); //$sequence->push('Bilbo'); Fatal error: Uncaught Krlove\Collection\Exception\FrozenException: Sequence is frozen and can not be changed $copy = $sequence->copy(); $copy->push('Bilbo'); foreach ($copy as $index => $value) { echo $index . ': ' . $value . PHP_EOL; }
0: Gandalf
1: Bilbo
用法
PHP 不支持泛型类型,因此无法定义如下属性。
private Map<int, string> $map; // invalid
必须编写一些额外的代码来确保使用正确类型的集合
class MyClass { /** * @var Map<int, string> */ private Map $map; public function __construct() { $this->map = Map::of('int', 'string'); } /** * @param Map<int, string> $map * @return void */ public function setMap(Map $map): void { if (!$map->isOf('int', 'string')) { // throw exception } $this->map = $map; } }