chemaclass/typed-arrays

此包已被废弃,不再维护。作者建议使用 chemaclass/typed-arrays 包。

PHP的泛型替代品。

1.1.0 2021-03-24 07:40 UTC

This package is auto-updated.

Last update: 2023-04-16 20:58:01 UTC


README

GitHub Build Status Scrutinizer Code Quality Scrutinizer Code Coverage Psalm Type-coverage Status MIT Software License

TypedArrays

PHP的泛型替代品。实现一个指定类型的数组。

为什么?

因为我们相信列表和映射是不同的。映射是键/值映射,列表是一系列项目。当保证数组中的所有元素都是已知类型时,类型安全性和易读性带来了许多好处。

要求

需要 PHP >= 7.4

安装

composer require chemaclass/typed-arrays

这个库是如何工作的?

以下是一个创建以实现特定类集合的类的示例。

final class ImmutableObjectList extends TypedArrays\AbstractTypedArray
{
    protected function typeToEnforce(): string
    {
        return Object::class;
    }

    protected function collectionType(): string
    {
        return self::COLLECTION_TYPE_LIST;
    }

    protected function isMutable(): bool
    {
        return false;
    }

    protected function isNullAllowed(): bool
    {
        return false;
    }
}

要强制执行的类型

您必须实现此方法。在这里,您定义此集合将处理哪种类型的对象

protected function typeToEnforce(): string
{
    return Object::class;
}

集合类型

有不同的集合类型。在这个库中,您可以找到多达三种不同类型: arraymaplist

默认情况下,集合是数组,但您可以通过在您的领域重写此函数来指定集合类型

protected function collectionType(): string
{
    return self::COLLECTION_TYPE_ARRAY;
}

数组

const COLLECTION_TYPE_ARRAY = 'array'

  • 类似于原生PHP数组。这允许您与原生PHP数组功能完全兼容。
  • 允许您混合列表和映射的概念。
  • 我们不鼓励使用它。这里只是为了以防您需要使用它。

映射

const COLLECTION_TYPE_MAP = 'map'

  • 将键映射到值的对象。
  • 映射不能包含重复的键;每个键最多映射到一个值。
  • 用户可以通过其键(键未排序)来搜索元素。

列表

const COLLECTION_TYPE_LIST = 'list'

  • 有序集合(也称为序列)。
  • 接口用户可以精确控制每个元素在列表中的位置。
  • 用户可以通过其整数索引(在列表中的位置)访问元素。

不可变性

可变集合在创建后可以更改,不可变集合不能。默认情况下,集合是可变的。

您可以通过在您的领域重写此函数来指定集合是否可变

protected function isMutable(): bool
{
    return false;
}

空值性

集合可以允许或不允许 null 项。默认情况下,集合不允许 null

您可以通过在您的领域重写此函数来指定集合是否允许可空项

protected function isNullAllowed(): bool
{
    return false;
}

预定义标量

如果您只需要字符串映射或整数列表,该库已包含所有可能的标量组合,用于

可变 标量 类型
ImmutableBooleanArray 布尔 数组
ImmutableBooleanList 布尔 列表
ImmutableBooleanMap 布尔 映射
ImmutableFloatArray 浮点 数组
ImmutableFloatList 浮点 列表
ImmutableFloatMap 浮点 映射
ImmutableIntegerArray 整数 数组
ImmutableIntegerList 整数 列表
ImmutableIntegerMap 整数 映射
ImmutableStringArray 字符串 数组
ImmutableStringList 字符串 列表
ImmutableStringMap 字符串 映射
MutableBooleanArray 布尔 数组
MutableBooleanList 布尔 列表
MutableBooleanMap 布尔 映射
MutableFloatArray 浮点 数组
MutableFloatList 浮点 列表
MutableFloatMap 浮点 映射
MutableIntegerArray 整数 数组
MutableIntegerList 整数 列表
MutableIntegerMap 整数 映射
MutableStringArray 字符串 数组
MutableStringList 字符串 列表
MutableStringMap 字符串 映射

开发

工作示例

您可以在example文件夹中检查一些工作示例

# The `ImmutableArticleList` is a list of Article instances
php example/articles.php

# The `IntMatrix` is a list of integer lists (List<List<int>>)
php example/int_matrix.php

# The `PublicationList` uses an interface as typeToEnforce()
php example/interface_publications.php

# The `MutableTranslationMap` is a map of string and nullables
php example/translations.php

Git钩子

使用./tools/git-hooks/init.sh启用git钩子