aziule/typed-collections

在数组或对象集合中添加一些类型检查

v1.0.0 2017-05-31 13:22 UTC

This package is not auto-updated.

Last update: 2024-09-29 02:23:55 UTC


README

TL;DR

typed-collections 是一个旨在提高开发者注意在PHP中操作数组时编写良好代码和文档的项目。

跳转到安装文档

PHP的动态类型特性可能导致差劲的开发者编写令人憎恶的代码。这在项目集合(数组)中尤为如此,其中只能依赖于PHPDoc(如果有的话,且是最新的且准确的)或变量的名称来猜测数组实际包含的内容

绝对最糟糕的情况

public function ($elements); // Too vague

糟糕 - 且不幸的是,这种情况太常见了

/**
* @param array $ips
*/
public function (array $ips); // Still too vague (can be associative, contain objects, etc.)

常见做法

/**
* @param MyObject[] $objects
*/
public function (array $objects); // Best practice

安装

通过Composer安装

composer require aziule/typed-collections

文档

支持的类型

该库支持PHP的大多数原始类型,以及用户定义的对象集合

  • 数组
  • 布尔值
  • 双精度浮点数
  • 整数
  • 字符串
  • 用户定义对象

使用方法

对于原始类型

原始类型集合将只允许存储此类类型的项(只有整数、只有布尔值等)。

以下是可用的原始集合类列表

Aziule\TypedCollections\ArrayCollection;
Aziule\TypedCollections\BooleanCollection;
Aziule\TypedCollections\DoubleCollection;
Aziule\TypedCollections\IntCollection;
Aziule\TypedCollections\StringCollection;

空集合

use Aziule\TypedCollections\IntCollection;

$collection = new IntCollection(); // Empty at that stage
$collection[] = 42;

foreach ($collection as $item) {
    // ...
}

预填充集合

use Aziule\TypedCollections\StringCollection;

$collection = new StringCollection([
    'my',
    'collection',
    'of',
    'strings',
]);

echo count($collection); // 4

对于用户定义的对象

存在两种方法用于创建和传递用户定义的对象集合

使用ObjectCollection

示例

use Aziule\TypedCollections\ObjectCollection;

class MyObject {
    // ...
}

$collection = new ObjectCollection(MyObject::class); // The collection is of type MyObject
$collection[] = new MyObject();
$collection[] = new \DateTime(); // Will throw an InvalidItemTypeException

只需将对象数组作为ObjectCollection构造函数的第二个参数传递以初始化它

use Aziule\TypedCollections\ObjectCollection;

class MyObject {
    // ...
}

$collection = new ObjectCollection(MyObject::class, [
    new MyObject(),
    new MyObject(),
]);

echo count($collection); // 2

如果您需要知道在ObjectCollection中嵌入的对象类型

use Aziule\TypedCollections\ObjectCollection;

$collection = new ObjectCollection(\stdClass::class);
echo $collection->getClass(); // 'stdClass'

创建一个自定义集合

如果您想要传递一个更严格类型的集合,您可以为所需的每种对象类型创建一个自定义集合。

示例

use \Aziule\TypedCollections\ObjectCollection;

class Item
{
    private $value;

    public function __construct($value)
    {
        $this->value = $value;
    }
}

class ItemCollection extends ObjectCollection
{
    public function __construct(array $items = [])
    {
        parent::__construct(Item::class, $items);
    }
}

$collection = new ItemCollection();
$collection[] = new Item('Foo');
$collection[] = new Item('Bar');

// And then use this collection
public function doSomething(ItemCollection $itemCollection)
{
    // ...
}

测试

./vendor/bin/phpunit