The library allows you to map data from the database to objects.
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:
- yiisoft/db to fetch data from the database
- yiisoft/hydrator to map data to objects.
composer req xepozz/remap
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
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.
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 ..."]
$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))];