bolt / 集合
各种集合的对象化实现
v1.1.2
2017-10-12 23:04 UTC
Requires
- php: ^5.5 || ^7.0
- bolt/common: ^1.0
- symfony/polyfill-php71: ^1.3
- webmozart/assert: ^1.0
Requires (Dev)
- bolt/codingstyle: ^2.0@dev
- escapestudios/symfony2-coding-standard: ^3.0@dev
- friendsofphp/php-cs-fixer: ^2.4
- phpunit/phpunit: ^4.8 || ^5.7 || ^6.4
- symfony/phpunit-bridge: ^3.3
README
这个库提供了对象和功能,帮助处理物品组和数据集。
查看API 文档。
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"
这些示例仅覆盖了功能的一半。有关更多信息,请参阅API 文档。
接受集合的所有方法都将接受其他 Bags
、arrays
、stdClass
和 Traversable
对象。这使得与任何类似集合的对象一起工作变得非常容易。
这不是已经完成了吗?
显然,其他人也认为PHP数组很糟糕,并尝试解决这个问题。
Symfony的 ParameterBag
是一个很好的基本 map(关联数组)容器,但在对项目进行更改和处理列表时却存在不足。
Doctrine的 ArrayCollection
也是另一个更健壮的选项。它在映射和列表方面表现良好,但由于需要与数据库集合接口,功能仍然有限。它还有一些让人烦恼的地方,比如 getKeys()
返回一个 array
而不是另一个 ArrayCollection
实例。