/remap

The library allows you to map data from the database to objects.

Primary LanguagePHP

Remap

The library allows you to map data from the database to objects.

Latest Stable Version Total Downloads phpunit codecov type-coverage

Description

The main goal is to simplify the process of querying long SQL queries and mapping the result to objects.

The mapper is designed to be used with querying of many objects at once. It uses \Generator to fetch data from the database and map it to objects one by one, so it's memory efficient.

Under the hood, it uses:

Installation

composer req xepozz/remap

Usage

Pass a class name and a query to the Remap.

final class Todo
{
    public int $id;
    public string $title;
    public int $status;
    public int $created_at;
}
$sql = 'SELECT id, title, status, created_at FROM todo WHERE id = :id LIMIT 1';
$params = ['id' => 1];

$remap->map(Todo::class, $sql, $params); // returns \Generator of Todo objects

Hydration

Using yiisoft/hydrator brings benefits of the Hydrator library: Attributes to modify the behavior of the hydration process.

use Yiisoft\Hydrator\Attribute\Parameter\Data;
use Yiisoft\Hydrator\Attribute\SkipHydration;

final class TodoModelHydrator
{
    #[Data('id')]
    public string $identifier;
    #[Data('title')]
    public string $text;
    public string $status;
    #[Data('created_at')]
    public string $date_created;
}

Or any other attributes compatible with the Hydrator library.

Tips

Define query-related methods in the class

final class Todo
{
    public int $id;
    public string $title;
    public int $status;
    public int $created_at;

    public static function selectOne(int $id): array
    {
        return [
            'SELECT id, title, status, created_at FROM todo WHERE id = :id LIMIT 1',
            ['id' => $id],
        ];
    }

    public static function selectAll(): string
    {
        return 'SELECT id, title, status, created_at FROM todo';
    }
}

And now it's easy to use:

$remap->map(Todo::class, ...Todo::selectOne(1)); // selectOne may return ['SELECT ...', ['id' => 1]]
$remap->map(Todo::class, Todo::selectOne(1)); // or shorter, without unpacking
$remap->map(Todo::class, Todo::selectAll());
$remap->map(...Todo::selectAll()); // selectAll may return [Todo::class, "SELECT ..."]

Unpack and store the result

$remap->map(...)

Always returns a generator. If you want to get an array of objects, use iterator_to_array:

$result = iterator_to_array(
    $remap->map(Todo::class, Todo::selectOne(1))
);

Or shorter:

$result = [...$remap->map(Todo::class, Todo::selectOne(1))];