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.
- With Symfony Flex
- Without Symfony Flex
- Non-Symfony Projects
Open a command console, enter your project directory, and execute:
composer require rekalogika/mapper
Step 1: Download the Bundle
Open a command console, enter your project directory, and execute the following command to download the latest stable version of this bundle:
composer require rekalogika/mapper
Step 2: Enable the Bundle
Then, enable the bundle by adding it to the list of registered bundles
in the config/bundles.php
file of your project:
return [
// ...
Rekalogika\Mapper\RekalogikaMapperBundle::class => ['all' => true],
];
Open a command console, enter your project directory, and execute:
composer require rekalogika/mapper
Many parts of this documentation assume you are using Symfony, and will need to be done differently in non-Symfony projects.
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:
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:
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 */