rekalogika / mapper

An object mapper for PHP and Symfony. Maps an object to another object. Primarily used for transforming an entity to a DTO and vice versa.
MIT License
27 stars 1 forks source link
api api-platform automapper dto mapper mapping php symfony transformation

rekalogika/mapper

rekalogika/mapper is an object mapper for PHP and Symfony, also commonly known as an automapper. It maps an object to another object. Primarily used to map an entity to a DTO, but also useful for other mapping purposes. It removes the complexity of mapping an object to another object, and even an object graph to another object graph.

Full documentation is available at rekalogika.dev/mapper.

Installation

composer require rekalogika/mapper

Usage

use App\Entity\Book;
use Rekalogika\Mapper\MapperInterface;

// map a single object:

/** @var MapperInterface $mapper */
/** @var Book $book */

$result = $mapper->map($book, BookDto::class);

// map a single object to an existing object:

$bookDto = new BookDto();
$mapper->map($book, $bookDto);

// map an iterable of objects:

/** @var IterableMapperInterface $iterableMapper */
/** @var iterable<Book> $books */

$bookDtos = $iterableMapper->mapIterable($books, BookDto::class);

Why Use a Mapper?

Why do we need to use a mapper to save a few keystrokes, and not just use something simple like this?

class BookDto
{
    public static function create(Book $book): self
    {
        $dto = new self();
        // ...

        return $dto;
    }
}

Everyone must have that idea at some point. However, as the project grows, the target classes (DTOs) may start to reference each other, and become a rich object graph. Your code will start to have many special cases, and is no longer as simple as you thought it would be. It becomes harder to maintain, and then eventually forces you to sit back and try to resolve the problem. When (if?) you successfully engineer a solution, you will end up with something that resembles a mapping framework anyway.

Mapping can be simple, but can also become a highly complex task. A mapper is created out of necessity to handle the complexity, not just as a means of saving a few keystrokes.

Features

General

Custom Mapping

Object Lazy-Loading

Arrays and Array-Like Objects

Array-Like Lazy-Loading

Development Experience (DX)

To-Do List

Documentation

rekalogika.dev/mapper

License

MIT