Skip to main content

Installation & Basic Usage

Install and use the mapper.

Installation

Make sure Composer is installed globally, as explained in the installation chapter of the Composer documentation.

Open a command console, enter your project directory, and execute:

composer require rekalogika/mapper

Getting the Mapper Service

In Symfony projects, you can simply autowire MapperInterface to your services and controllers just as you would do with any other service.

In non-Symfony projects, you can use the MapperFactory to get the mapper service:

use Rekalogika\Mapper\MapperFactory;

$mapperFactory = new MapperFactory();
$mapper = $mapperFactory->getMapper();

Mapping a Single Object

Suppose you have a Book entity:

src/Entity/Book.php
namespace App\Entity;

class Book
{
public function __construct(
private int $id,
private string $title,
private string $author,
) {
}

public function getId(): ?int
{
return $this->id;
}

public function getTitle(): ?string
{
return $this->title;
}

public function getAuthor(): ?string
{
return $this->author;
}
}

And need to map it to the BookDto data transfer object:

src/Dto/BookDto.php
namespace App\Dto;

class BookDto
{
public string $id;
public string $title;
public string $author;
}

You can simply do:

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

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

$result = $mapper->map($book, BookDto::class);
/** @var BookDto $result */

// or map to an existing object

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

Mapping Multiple Objects

You can also map an iterable of objects of the same type by using IterableMapperInterface.

In Symfony projects, you can simply autowire the service IterableMapperInterface.

In non-Symfony projects, you can use the MapperFactory to get the iterable mapper service:

use Rekalogika\Mapper\MapperFactory;

$mapperFactory = new MapperFactory();
$iterableMapper = $mapperFactory->getIterableMapper();

Then, you can use the mapIterable() method to map an iterable of Book entities to an iterable of BookDto objects:

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

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

$result = $iterableMapper->mapIterable($books, BookDto::class);
/** @var iterable<BookDto> $result */