silvanus/collection

此包已被废弃且不再维护。未建议替代包。

为PHP提供的类型化集合数组。

v1.0.0 2021-03-20 12:31 UTC

This package is auto-updated.

Last update: 2024-06-11 17:59:43 UTC


README

PHP的最简类型化数组/集合。

PHP有许多集合库,但没有一个是完全符合我需求的。大多数集合库添加了许多我不需要的额外功能。

集合的作用

  • 简单 & 轻量级
  • 数组语法
  • 允许为对象数组使用类型提示

动机

PHP中的类型提示 "array" 并非非常具有描述性。有时使用类似集合的类型化数组更合适。这个库提供了常见的父类,以减少创建这些集合的样板代码。

安装

composer require silvanus/collection

使用

创建一个扩展抽象父类的自定义集合类。

<?php

// Parent class.
use Silvanus\Collection\AbstractCollection;

class DummyCollection extends AbstractCollection
{
    /**
     * Provide your class with getType function.
     * Return fully qualified namespace of your tpye. 
     */
    protected function getType() : string {
        return 'Acme\App\DummyEntity';
    }
}

就这样。你的集合像数组一样工作,但只接受你定义的类型。

<?php

// Your collection
use Acme\App\DummyCollection;

// Your object.
use Acme\App\DummyEntity;

$collection = new DummyCollection();

// All good.
$collection[] = new DummyEntity(1);
$collection[] = new DummyEntity(2);

// Exception thrown
$collection[] = new DateTime();

你还可以将数组转换为集合。

<?php

// Your collection
use Acme\App\DummyCollection;

// Your object.
use Acme\App\DummyEntity;

$array = array( new DummyEntity(1), new DummyEntity(2), new DummyEntity(3) );

// Will throw exceptions if incorrect types in array.
$collection = new DummyCollection( $array );