hyqo / collection
1.0.0
2023-02-22 12:13 UTC
Requires
- php: ^8.2
- ext-json: *
Requires (Dev)
- phpunit/phpunit: ^10.0
README
支持泛型的基本集合
安装
composer require hyqo/collection
用法
例如,我们有一个 Product
类,我们想要将其包装到集合中
class Product { public $title; public $amount; public function __construct(string $title, int $amount){ $this->title = $title; $this->amount = $amount; } }
创建集合
use \Hyqo\Collection\Collection; use function \Hyqo\Collection\collect; $collection = new Collection([new Product('foo', 10), new Product('bar', 2)]); $collection = collect([new Product('foo', 10), new Product('bar', 2)]);
自动补全
有三种代码自动补全的方法
1. 创建包含项目的集合(非空)
use Hyqo\Collection\Collection; $collection = new Collection([new Product('foo', 10), new Product('bar', 2)]);
2. 使用带有泛型注解的 PHPDoc
use Hyqo\Collection\Collection; /** @var Collection<Product> $collection */ $collection = new Collection();
3. 使用带有 @extends
注解的您自己的类
use Hyqo\Collection\Collection; /** @extends Collection<Product> */ class ProductCollection extends Collection { } $collection = new ProductCollection();
现在您已经有了自动补全(见上面的图片)
方法
add
function add($item): static
向集合中添加新项目
$collection->add($item);
get
function get(int $index): T|null
通过索引获取集合中的项目
$collection->get(0);
each
function each(callable $closure): static<T>
将每个项目传递给闭包
$collection->each(function(Product $product) { // do something });
map
function map(callable $closure): static<T>
将每个项目传递给闭包并创建结果的新集合。
闭包必须返回 T
或 \Generator<T>
类型的值
$collection->map(function(Product $product) { // do something return $product; });
reduce
function reduce(callable $closure, $initial = null): mixed|null
将集合缩减为单个值
$collection = new Collection([new Product('foo', 10), new Product('bar', 2)]); $amount = $collection->reduce(function($carry, Product $product) { return $carry + $product->amount; }); // 4
slice
function slice(int $first, ?int $length = null): static<T>
创建一个包含当前集合切片的新集合
$collection->slice(3);
copy
function copy(): static<T>
创建一个包含相同元素的新集合(slice(0)
的别称)
$collection->copy();
chunk
function chunk(int $length): \Generator<static<T>>
将集合分割成多个给定长度的集合。最后一个可能包含较少的元素
$collection->chunk(10);
filter
function filter(callable $closure): static<T>
将每个项目传递给闭包并创建一个新集合,其中其结果将为 true
。
闭包必须返回 bool
值
$collection->filter(function(Product $product){ return $product->amount > 1; });
toArray
function toArray(?callable $closure = null): array
返回集合中的所有项目。您可以通过闭包转换数组的每个元素。如果您需要一个关联数组,闭包应返回一个生成键/值对的生成器。
闭包必须返回任何值或 \Generator<array-key,mixed>
$collection->toArray(); // [Product, Product] $collection->toArray(function(Product $product) { return $product->title; }); // ['foo', 'bar'] $collection->toArray(function(Product $product): \Generator { yield $product->title => $product->amount; }); // ['foo'=>10, 'bar'=>2]