goksagun / collection
一个提供管理及操作集合功能的PHP集合库。
v0.2.7
2024-04-24 10:58 UTC
Requires
- php: ^8.2
Requires (Dev)
- phpunit/phpunit: ^11.1
- symfony/var-dumper: ^7.0
README
一个提供管理及操作产品集合功能的PHP集合库。
特性
- 创建一个物品集合
- 向集合中添加一个物品
- 遍历集合,对每个物品应用一个函数
- 根据谓词过滤集合
- 从集合中的每个物品中提取特定属性
- 将集合缩减为单个值
- 根据自定义比较函数对集合进行排序
安装
使用 Composer 安装此库
composer require goksagun/collection
用法
以下是一个使用此库的基本示例
<?php namespace Acme; class Product { public function __construct ( private string $name, private float $price ) {} public function getName(): string { return $this->name; } public function getPrice(): float { return $this->price; } }
<?php namespace Acme; use Acme\Product; use Goksagun\Collection\Collection; /** * @implements Collection<Product> */ final class ProductCollection extends Collection { public function __construct(Product ...$items) { parent::__construct(...$items); } }
<?php namespace Acme; use Acme\Product; use Acme\ProductCollection; $collection = new ProductCollection( new Product('Product 1', 100.99), new Product('Product 2', 200.99), new Product('Product 3', 300.99), ); $total = $collection ->map(function (Product $product) { return new Product($product->getName(), $product->getPrice() * 1.18); }) ->each(function (\Goksagun\Collection\Test\Fixtures\Product $product, int $index) { echo "Product {$index}: {$product->getName()} - {$product->getPrice()}\n"; }) ->filter(function (Product $product) { return $product->getPrice() > 300; }) ->pluck('price') ->reduce(function (float $total, float $price) { return $total + $price; }, 0); echo "Total: {$total}\n"; // Product 0: Product 1 - 119.1682 // Product 1: Product 2 - 237.1682 // Product 2: Product 3 - 355.1682 // Product 0: Product 3 - 355.1682 // Total: 355.1682
测试
使用以下命令运行测试
composer test
许可证
本项目采用MIT许可证 - 请参阅LICENSE文件以获取详细信息。