jcrowe / type-safe-collection
对 Illuminate/Collection 的轻量级封装,允许对集合元素施加类型约束
v7.1
2020-05-05 19:09 UTC
Requires
- php: >=7.0
- illuminate/support: ^7.0
Requires (Dev)
- mockery/mockery: dev-master
- phpunit/phpunit: 4.8.*
- satooshi/php-coveralls: dev-master
This package is auto-updated.
Last update: 2024-09-06 04:21:55 UTC
README
TypeSafeCollection 是对 Illuminate 集合对象的轻量级封装,允许在集合中轻松执行类型保护。
use JCrowe\TypeSafeCollection\TypeSafeCollection; class MovieLibrary extends TypeSafeCollection { // list of classes that can be added to the collection protected $allowedClasses = [Watchable::class, Rentable::class]; } $myLibrary = new MovieLibrary([ new WatchableMovie(), new RentableDVD(), new ReadableBook() // throws \InvalidArgumentProvided exception ]); $myLibrary = new MovieLibrary(); $myLibarry->push(new RentableDVD()); $myLibrary->push(new ReadableBook()); // throws \InvalidArgumentProvided exception
自定义检查
class MovieLibrary extends TypeSafeCollection { // list of classes that can be added to the collection protected $allowedClasses = [Watchable::class, Rentable::class]; // this function will be called whenever a new // element is being added to the collection protected function onAddNewElement($element) { if (!$element->isAvailable()) { return false; // or throw exception } } }
忽略无效类型,不抛出异常
class MovieLibrary extends TypeSafeCollection { // list of classes that can be added to the collection protected $allowedClasses = [Watchable::class, Rentable::class]; // if set to true no exception will be thrown when // attempting to add an invalid value. protected $ignoreInvalidElements = true; } $myLibrary = new MovieLibrary(); $myLibrary->put('my_rentable', new RentableDVD()); $myLibrary->get('my_rentable'); // RentableDVD object $myLibrary->put('my_readable', new ReadableBook()); // no exception is thrown $myLibrary->get('my_readable'); // null
安装
composer require jcrowe/type-safe-collection
{ "require": { "jcrowe/type-safe-collection": "~1.0" } }