camelot / collection
面向对象的多种集合实现
v1.1.1
2021-11-08 13:36 UTC
Requires
- php: ^7.1.3 || ^8.0
- ext-json: *
- camelot/common: ^1.0 || ^2.0
- symfony/polyfill-php71: ^1.3
- webmozart/assert: ^1.10
Requires (Dev)
- camelot/coding-style: ^3.0
- escapestudios/symfony2-coding-standard: ^3.0
- friendsofphp/php-cs-fixer: ^3.0
- phpunit/phpunit: ^9.5
- symfony/phpunit-bridge: ^5.3
This package is auto-updated.
Last update: 2024-09-08 19:36:00 UTC
README
此库提供对象和功能,帮助处理项目组和数据集。
查看[API文档][api-docs]。
Bag
和MutableBag
这些是数组的面向对象实现。
这些类目标
- 提供与内置数组方法相当的功能
- 提供内置数组方法中缺少的有用功能
- 提供类似流式操作的使用体验
- 使代码实现更易于阅读
示例
$arr = [ 'debug' => true, 'color' => 'blue', 'db' => [ 'driver' => 'sqlite', ], ]; $bag = Bag::from($arr) ->defaults([ 'debug' => false, 'color' => 'green', ]) ->replace([ 'color' => 'red', ]) ; $bag->get('debug'); // true $bag->getPath('db/driver'); // "sqlite" $bag->keys()->join(', '); // "debug, color, db" $bag->isAssociative(); // true
$colors = MutableBag::of('red', 'blue', 'yellow') ->merge(['green', 'orange']) ; $colors->isIndexed(); // true $colors->indexOf('yellow'); // 2 $colors[2]; // "yellow" $colors->prepend('purple'); $colors[] = 'pink'; $colors->first(); // "purple" $colors->last(); // "pink" $colors->shuffle()->first(); // one of the colors $colors->chunk(2); // Bags represented as arrays: // [ ['purple', 'red'], ['blue', 'yellow'], ['green, 'orange'], ['pink'] ] $colors->removeFirst(); // "purple" $colors->removeFirst(); // "red"
所有接受集合的方法都接受其他Bags
、arrays
、stdClass
和Traversable
对象。这使得处理任何类似集合的对象变得非常容易。
这不是已经完成了吗?
显然,其他人也认为PHP数组很糟糕,并试图解决这个问题。
Symfony的ParameterBag
是一个很好的基本映射(关联数组)容器,但在对项目进行更改和处理列表方面存在不足。
Doctrine的ArrayCollection
也是一个更健壮的选项。它在映射和列表方面表现良好,但由于需要与数据库集合接口,因此功能有限。它还有一些令人烦恼的地方,比如getKeys()
返回一个array
而不是另一个ArrayCollection
实例。