tijmenwierenga/repositories

一套具有超级功能的创建存储库的实用工具。

v0.3.0 2021-06-08 17:49 UTC

This package is auto-updated.

Last update: 2024-09-25 22:48:59 UTC


README

内存中的存储库

TijmenWierenga\Repositories\InMemoryRepository是一个基于数组的简单存储,执行持久化相关操作。

all(): T[]

返回存储库中存储的所有项。

$users = [
    new User(1),
    new User(2),
    new User(3),
];

$repository = new InMemoryRepository($users);

$users = $repository->all(); // returns an array with all users.

find(Closure $criteria): T|null

返回符合条件的第一项。如果没有找到匹配项,则返回null

$users = [
    new User(1),
    new User(2),
    new User(3),
];

$repository = new InMemoryRepository($users);

$user = $repository->find(fn (User $user): bool => $user->id === 1); // Returns user with ID of 1.

findMany(Closure $criteria): T[]

返回所有符合条件的项目。

$users = [
    new User(1),
    new User(2),
    new User(3),
];

$repository = new InMemoryRepository($users);

$user = $repository->findMany(fn (User $user): bool => $user->id > 1); // Returns all users with a ID greater than 1.

add(T $item): void

将新项目添加到集合中。

$repository = new InMemoryRepository();

$repository->add(new User(1)); // User is now added to the collection.

remove(Closure $criteria): void

删除所有符合条件的项目。

$users = [
    new User(1),
    new User(2),
    new User(3),
];

$repository = new InMemoryRepository($users);

$repository->remove(fn (User $user): bool => $user->id === 1); // Removes user with an ID of 1.

first(): T|null

返回集合中的第一项。如果集合为空,则返回null

$users = [
    new User(1),
    new User(2),
    new User(3),
];

$repository = new InMemoryRepository($users);

$repository->first(); // Returns User(1)

last(): T|null

返回集合中的最后一项。如果集合为空,则返回null

$users = [
    new User(1),
    new User(2),
    new User(3),
];

$repository = new InMemoryRepository($users);

$repository->last(); // Returns User(3)

map(Closure $function): U

返回一个基于闭包返回值的新存储库实例。

$users = [
    new User(1),
    new User(2),
    new User(3),
];

$repository = new InMemoryRepository($users);

$usernames = $repository->map(fn (User $user): string => $user->username()); // Returns InMemoryRepository<string> with usernames