reptily/array-list

PHP的ArrayList

0.2.2 2023-10-26 07:29 UTC

This package is auto-updated.

Last update: 2024-09-10 12:01:04 UTC


README

composer require reptily/array-list

这个库解决了什么问题?

PHP语言中没有内置的机制来创建列表。关联数组不能保证其元素是类型的。

示例

function show(array $items)
{
    foreach ($items as $item) {
        echo $item->id . PHP_EOL;
    }
}

在这个例子中,我们不保证所有元素都是必要的对象,也不保证数组没有附件。

function show(ArrayList $items)
{
    foreach ($items as $item) {
        echo $item->id . PHP_EOL;
    }
}

代码没有变大,但出现了类型化。 ArrayList 负责所有类型和数据访问问题。我们可以确信数组中的所有类型都是正确的,而且不需要进行不必要的检查。

示例

更多示例在目录 /example

仅整数

$list = new ArrayList(ArrayList::TYPE_INTEGER, [1, 2, 3]);
// or
$list = new ArrayListInteger([1, 2, 3]);

foreach ($list as $item) {
    echo $item . PHP_EOL;
}

如果我们需要一个对象的集合

class UserList extends ArrayList {
    public function __construct(?array $items = null)
    {
        parent::__construct(UserDTO::class, $items);
    }
};

class UserDTO {
    public $id;
    public $name;

    public function __construct($id, $name)
    {
        $this->id = $id;
        $this->name = $name;
    }
}

$userList = new UserList();
$userList->add(new UserDTO(1, 'bob'));
$userList->add(new UserDTO(2, 'job'));

function echoDTOs(UserList $list): void
{
    $list->forEach(function ($item) {
        echo sprintf("id:%d name:%s" . PHP_EOL, $item->id, $item->name);
    });
}

作为对象使用

$ids = new ArrayListInteger([1, 2, 3]);
$ids->add(4);

function show(ArrayListInteger $ids)
{
    $ids->forEach(function($id) {
        echo $id . PHP_EOL;
    });
}
show();

作为数组使用

$ids = new ArrayListInteger([1, 2, 3]);
$ids[] = 4;

function show(ArrayListInteger $ids)
{
    foreach ($ids as $id) {
        echo $id;
    }
}
show();

方法

add(mixed $item): void

向数组中添加一个元素

count(): int

返回数组中的元素数量

isEmpty(): bool

返回是否为空

indexOf(mixed $element): ?int

在数组中搜索匹配项,如果找到则返回索引,如果没有找到则返回null

lastIndexOf(): ?int

将返回数组中的最后一个索引,如果数组为空则返回null

clone(): self

克隆一个对象

toArray(): array

转换为关联数组

get(int $index): mixed

通过索引返回一个元素,如果没有元素,将抛出异常

set(int $index, mixed $item): void

通过索引设置元素的值

exists(int $index): bool

通过索引检查元素是否存在

remove(int $index): void

通过索引删除元素

clear(): void

清理数组

forEach(): callback(mixed $item, int $index)

为数组中的每个元素返回一个回调

sort(string $sort = 'asc'|'desc'): void

排序数组

支持类

ArrayListInteger

创建一个必须所有元素都是整数的列表

ArrayListString

创建一个必须所有元素都是字符串的列表

ArrayListFloat

创建一个必须所有元素都是浮点数的列表

常量

按类型定义常量

  • TYPE_STRING
  • TYPE_INTEGER
  • TYPE_BOOLEAN
  • TYPE_FLOAT

按排序定义常量

  • SORT_DESC
  • SORT_ASC