kurilka / maperus
Mapper for objects
0.0.1
2026-06-04 22:25 UTC
This package is not auto-updated.
Last update: 2026-06-04 23:22:49 UTC
README
author: TheWhatis lang: ru
title: Maperus - Маппер для объектов
Описание
Пакет для маппинга одних объектов к другим (чем-то схож с transformer-ами).
Установка
composer require awe/maperus
Использование
Объект Dto
<?php declare(strict_types=1);
class PostDto
{
public function construct(
public readonly string $title,
public readonly string $content,
) {
// ...
}
}
Объект сущности
<?php declare(strict_types=1);
use SomeORM\Entity;
class Post extends Entity
{
private string $title;
private string $content;
public function getTitle(): string
{
return $this->title;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
public function getContent(): string
{
return $this->content;
}
public function setContent(string $content): self
{
$this->content = $content;
return $this;
}
}
Mapper
<?php declare(strict_types=1);
use Maperus\AbstractMapper;
use Maperus\Attribute\Mapper;
/**
* @extends AbstractMapper<PostDto, Post>
*/
#[Mapper(source: PostDto::class, target: Post::class)]
class PostDtoToPostMapper extends AbstractMapper
{
/**
* @param Postdto $source
* @return Post
*/
public function create(object $source): object
{
return new Post;
}
/**
* @param PostDto $source
* @param Post $target
*/
public function populate(object $source, object $target): object
{
$target->setTitle($source->title);
$target->setContent($source->content);
}
}
Иницилизация и использование
<?php declare(strict_types=1);
use Maperus\MapperProcessor;
use Maperus\MapperRegistry;
use Mapeurs\MapperDecoratorFactoryRegistry;
$mapperProcessor = new MapperProcessor(
mapperRegistry: $mapperRegistry = new MapperRegistry,
// Опционально
// $mapperDecoratorFactoryRegistry = new MapperDecoratorFactoryRegistry,
);
$mapperRegistry->addMapper(new PostDtoToPostMapper);
// $mapperDecoratorFactoryRegistry->addfactory(...)
$postDto = new PostDto(
title: 'Title',
content: 'Content',
);
$post = $mapperProcessor->map($postDto, Post::class);