pinkcrab/collection

灵活且可扩展的集合

0.2.0 2021-09-21 13:57 UTC

This package is auto-updated.

Last update: 2024-09-21 20:59:17 UTC


README

alt text Open Source Love codecov

版本 0.2.0

这个库是从PinkCrab插件框架(Perique)提取出来的

为什么?

提供具有所有预期功能的基本集合,包括过滤、映射、折叠、排序和比较。同时,它也是可扩展的,可以创建自定义集合,这些集合可以扩展并具有类型。这是一个相当简单但可扩展的集合。

安装

composer install pink-crab/collection

基本用法

有关更多详细信息和方法示例,请参阅./docs

$collection = new Collection(['1',2,'3']);
$collection->push(4);
$collection->apply(fn($e) => (string) $e);
var_dump($collection); // ['1','2','3','4'];
$collection = new Collection([1,2,3,4,5,6,7,8,9,10]);
$collection->filter(fn($e) => $e % 2 == 0);
var_dump($collection); // [2,4,6,8,10];

可扩展特性

Collection包包含一些特性,可以在创建自定义集合时使用。这些特性可以通过匿名类即时创建,或者通过定义完整的类来创建。

$indexed_collection = new class() extends \PinkCrab\Collection\Collection {
	use \PinkCrab\Collection\Traits\Indexed;
};

$indexed_collection->set( 'key1', 'value1' );
$indexed_collection->has( 'key1' ); //true
var_dump( $indexed_collection );


// As a full class.
class Indexed_Collection extends \PinkCrab\Collection\Collection {
	use \PinkCrab\Collection\Traits\Indexed;
};

$indexed_collection = new Indexed_Collection();
$indexed_collection->set( 'key1', 'value1' );
$indexed_collection->has( 'key1' ); //true
var_dump( $indexed_collection );

类型化与映射集合

<?php

class Post_Collection extends Collection {
	// Filter out anything not matching.
	protected function map_construct( array $data ): array {
		return array_filter(fn($e): bool => is_a($data, \WP_Post::class));
	}
}

$posts = Post_Collection::from([$post1, null, $post2, false, WP_Error]);
var_dump($posts->to_array()); // [$post1, $post2];

$collection->each(function($e){
	print $e->post_title . PHP_EOL;
}); 
// Post Title 1
// Post Title 2

许可证

MIT许可证 https://open-source.org.cn/licenses/mit-license.html

变更日志

  • 0.2.0 - 添加了针对diff和intersect的选项回调,包括基于对象实例或值的辅助函数。还包括group_by()方法。
  • 0.1.0 - 添加了Has_ArrayAccess和Is_Iterable特性,以便实现接口。添加了来自现有GitBook仓库的文档。
  • 0.0.0 - 从PinkCrab插件框架中提取出来,作为一个独立的包。