jarjak/collection

不可变、类型感知的PHP集合。

0.4.2 2022-04-17 00:32 UTC

This package is auto-updated.

Last update: 2024-09-17 06:12:47 UTC


README

实现了map、flatMap、reduce、sort、unique等方法的集合模式。可序列化为JSON。

要求

PHP >= 7.1

安装

此包通过packagist的composer可用。

composer require jarjak/collection

用法

基本用法

use JarJak\Collection\Collection;

$dateArray = [
    new DateTime(),
    new DateTimeImmutable(),
];

$dateCollection = new Collection(...$dateArray);
# or
$dateCollection = Collection::from($dateArray);

# then do what you know from other collection implementations
$plusYears = $dateCollection
    ->map(fn($date) => $date->modify('+1 year'))
    ->toArray();

添加类型检查功能

这个实现中最酷的特性之一是你可以设置自己的特定类型感知集合(可以想象成聚合/仓库)。然后你可以封装对一组相同类型对象执行任何自定义操作(而不是在控制器/服务中的某个foreach循环中执行)。

use JarJak\Collection\Collection;

class DateCollection extends Collection
{
    // accept only date objects
    public function __construct(DateTimeInterface ...$items)
    {
        parent::__construct(...$items);
    }
    
    // you can personalize it by adding custom methods too!
    public function getMaxYear(): int
    {
        return $this->reduce(
            0, 
            function (int $current, DateTimeInterface $date): int {
                $year = (int) $date->format('Y');
                return $current > $year ? $current : $year; 
            }
        );
    }
}

# this is acceptable
$dateCollection = new DateCollection(
    new DateTime(),
    new DateTimeImmutable()
);
# this will result in an error
$dateCollection = new DateCollection(
    new DateTime(),
    new DateTimeImmutable(),
    date('now')
);

# then this will work
$plusYears = $dateCollection->map(fn($date) => $date->modify('+1 year'));
# but this won't
$dateStrings = $dateCollection->map(fn($date) => $date->format('Y-m-d'));
# unless you explicitly disable type check (which effectively sends you back to the base Collection class)
$dateStrings = $dateCollection
    ->disableTypeCheck()
    ->map(fn($date) => $date->format('Y-m-d'));

灵感来源

https://github.com/jkoudys/immutable.php