maike/iterable

一个抽象类,赋予你的类可迭代的能力

1.1.0 2020-09-02 16:35 UTC

This package is auto-updated.

Last update: 2024-09-05 22:03:21 UTC


README

在其他语言中,例如Java,你可以使用只允许一种类型的Collections。例如在TypeScript中,我们可以这样做

public getItems(): Array<Items>
{
  return this.items;
}

不幸的是,PHP没有这样的东西,这就是我创建这个抽象类的原因

安装

此包通过composer安装

composer require maike/iterable

用法

为了在PHP中实现只允许一种类型的Collection,我们需要创建一个类。以下示例中,我创建了一个继承自Iterable\Iterator抽象类的Collection类

创建一个Collection类

use Iterable\Iterator;

class DateTimeCollection extends Iterator {
  public function __construct(\DateTime ...$items)
  {
    parent::__construct($items);
  }
}

以上代码我们实现了两个目标

  1. 我们有一个只允许DateTime对象的集合。
  2. 我们可以像在数组中一样迭代我们的集合。请看以下示例
$datesCollection = new DateTimeCollection(
  new \DateTime,
  new \DateTime,
  new \DateTime,
);

foreach ($datesCollection as $key => $date) {
  // Do whatever you want
}

贡献

运行构建

make build

运行测试

make tests