kartavik / typed-collection
类型化集合的实现
v2.0.0RC1
2018-11-08 09:44 UTC
Requires
- php: >=7.1
Requires (Dev)
- phpunit/phpunit: ^7.4
- squizlabs/php_codesniffer: ^3.3.2
This package is auto-updated.
Last update: 2024-09-09 13:48:20 UTC
README
强类型泛型集合实现
安装
使用 composer 安装
composer require kartavik/typed-collection
用法
动态
- 内部类型
<?php use kartavik\Support\Collection; use kartavik\Support\Strict; $items = [1, 2, 3, 4,]; $collection = new Collection(Strict::integer(), $items); // Return instance of typed collection $collection = Collection::{'integer'}($items); // Work same as constructor // Another examples // string Collection::{Strict::STRING}(['str1', 'str2']); // float Collection::{Strict::FLOAT}([12.3, 23.5, 3., 54.321,]); // array Collection::{Strict::ARRAYABLE}([[1, 2], ['str1'], [123.456]]); // boolean Collection::{Strict::BOOLEAN}([true, false]); // object Collection::{Strict::OBJECT}([new stdClass(), new Exception()]);
- 用户类型
<?php use kartavik\Support\Collection; use kartavik\Support\Strict; // You can put name of class to static call // In this case collection can take only stdClass // It will work with any declared classes $collection = Collection::{stdClass::class}([]); // you can also do it with constructor $collection = new Collection(Strict::object(stdClass::class), []); // Strict class also support static call for class name $strict = Strict::{stdClass::class}(); $collection = new Collection($strict, []);
扩展
StringCollection.php:
<?php use kartavik\Support; class StringCollection extends Support\Collection { public function __construct(array $items) { // do something parent::__construct(Support\Strict::string(), $items); } }
强类型在哪里?
类 Strict 帮助集合验证元素类型;
如果你在任何时候试图将非元素类型的元素放入集合,你会得到 Exception\Validation
如果你试图设置特定类型,你会捕获 Exception\UnprocessedType