gamez / typed-collection
基于 Laravel Collections 的类型安全集合
7.1.0
2024-03-17 23:43 UTC
Requires
- illuminate/collections: ^10.0 || ^11.0
Requires (Dev)
- phpstan/phpstan: ^1.10.62
- phpunit/phpunit: ^10.5.13
README
注意
Laravel 11 添加了 ensure()
集合方法,该方法验证集合中的所有元素是否为给定的类型或类型列表。然而,这种验证不能防止在以后添加不同类型的项。
安装
可以使用 Composer 安装此包
$ composer require gamez/typed-collection
使用方法
class Person { public $name; public function __construct($name) { $this->name = $name; } } $taylor = new Person('Taylor'); $jeffrey = new Person('Jeffrey');
类型化集合
use Gamez\Illuminate\Support\TypedCollection; class People extends TypedCollection { protected static $allowedTypes = [Person::class]; } $people = People::make([$taylor, $jeffrey]) ->each(function (Person $person) { printf("This is %s.\n", $person->name); }); /* Output: This is Taylor. This is Jeffrey. */ try { People::make('Not a person'); } catch (InvalidArgumentException $e) { echo $e->getMessage().PHP_EOL; } /* Output: Output: A People collection only accepts items of the following type(s): Person. */
懒类型集合
use Gamez\Illuminate\Support\LazyTypedCollection; class LazyPeople extends LazyTypedCollection { protected static $allowedTypes = [Person::class]; } $lazyPeople = LazyPeople::make([$taylor, $jeffrey]) ->each(function (Person $person) { printf("This is %s.\n", $person->name); }); /* Output: This is Lazy Taylor. This is Lazy Jeffrey. */ try { LazyPeople::make('Nope!'); } catch (InvalidArgumentException $e) { echo $e->getMessage().PHP_EOL; } /* Output: Output: A People collection only accepts objects of the following type(s): Person. */
支持类型
支持类型包括类字符串,如 Person::class
,或由 get_debug_type()
函数 识别的类型,例如 int
、float
、string
、bool
和 array
。
辅助函数
typedCollect()
辅助函数允许您动态地即时创建类型化集合
$dateTimes = typedCollect([new DateTime(), new DateTime()], DateTimeInterface::class);
有关如何使用 Laravel 集合的更多信息,请参阅 官方文档。