PHPackages                             ok/dto-annotation-mapper - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. ok/dto-annotation-mapper

ActiveLibrary[Database &amp; ORM](/categories/database)

ok/dto-annotation-mapper
========================

Data mapper

2.3(4y ago)31.2kMITPHPPHP &gt;=7.4

Since Mar 11Pushed 4y ago1 watchersCompare

[ Source](https://github.com/GitHubHubus/dto-annotation-mapper)[ Packagist](https://packagist.org/packages/ok/dto-annotation-mapper)[ Docs](https://github.com/GitHubHubus/dto)[ RSS](/packages/ok-dto-annotation-mapper/feed)WikiDiscussions master Synced today

READMEChangelogDependencies (2)Versions (10)Used By (0)

Annotation entity mapper based on Doctrine
==========================================

[](#annotation-entity-mapper-based-on-doctrine)

[![Latest Stable Version](https://camo.githubusercontent.com/616a74db8bbf9db193a0df06b8510fd5b005dc4c65275fdcee094d88ab56f1fe/68747470733a2f2f706f7365722e707567782e6f72672f6f6b2f64746f2d616e6e6f746174696f6e2d6d61707065722f76657273696f6e)](https://packagist.org/packages/ok/dto-annotation-mapper)[![Total Downloads](https://camo.githubusercontent.com/163b17c36f725aa836dd5317d0731d977e35a70565e31ad9233108de948eb81a/68747470733a2f2f706f7365722e707567782e6f72672f6f6b2f64746f2d616e6e6f746174696f6e2d6d61707065722f646f776e6c6f616473)](https://packagist.org/packages/ok/dto-annotation-mappert)[![License](https://camo.githubusercontent.com/3fbdee08267b066b0d73b2a98a55a6d6608f31cdd053d9b97abc220a190a017a/68747470733a2f2f706f7365722e707567782e6f72672f6f6b2f64746f2d616e6e6f746174696f6e2d6d61707065722f6c6963656e7365)](https://packagist.org/packages/ok/dto-annotation-mapper)

This library intended for auto fill entity object from input dataset based on annotations.

Purpose
-------

[](#purpose)

This library could be useful if you have several cases, when you fill entity from an array data.

For example, you retrieve data from client and create new entity and another way you get this entity from import file.

Instead of create separate services to filling entity from array data set you could just specify entity fields for filling and pass only those properties which you need.

Requirements
------------

[](#requirements)

- PHP 7.4+
- Doctrine ORM 2+

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require ok/dto-annotation-mapper
```

For Symfony project: Register AnnotationMapper as service in `services.yml`:

```
OK\Dto\MapperInterface:
   class: OK\Dto\AnnotationMapper
   autowire: true
```

For other just init new mapper object

```
use Doctrine\Common\Annotations\AnnotationReader;

$mapper = new AnnotationMapper(new AnnotationReader(), $entityManager);
```

Usage
-----

[](#usage)

At first you need to mark your setters in doctrine entity with [DTO](https://github.com/GitHubHubus/dto-annotation-mapper/blob/master/src/OK/Dto/Annotation/DTO.php) annotation

```
/**
 * @ORM\Entity(repositoryClass="App\Repository\ProductRepository")
 */
class Product
{
    /**
     * @var string
     *
     * @ORM\Column(type="string", nullable=true)
     */
    protected $article;

    /**
     * @var Material
     *
     * @ORM\ManyToOne(targetEntity="App\Entity\Product\Options\Material")
     */
    protected $material;

    /**
     * @DTO(name="article", type="string")
     */
    public function setArticle(?string $article)
    {
        $this->article = $article;
    }

    /**
     * @DTO(name="material", type="App\Entity\Product\Options\Material", relation="ManyToOne")
     */
    public function setMaterial(?Material $material)
    {
        $this->material = $material;
    }
```

Then just pass input data with object to `fillObject` method in controller like this (Example for Symfony project, but you can use it with any framework or without it):

```
    /**
     * @Route("/products/{id}", name="api_product_patch", methods={"PATCH"})
     */
    public function updateProductAction(Request $request, Product $product, MapperInterface $mapper): JsonResponse
    {
        $data = $this->getRequestData($request);

        $updatedProduct = $mapper->fillObject($product, $data);

        /* Do validation and other actions if need */

        $this->getDoctrine()->getManager()->flush();

        return $this->json($updatedProduct);
    }
```

That's it! Your entity will updated with new data.

Available simple types: `string`, `float`, `bool`, `boolean`, `int`, `integer`, `datetime`, `array`. Trying to use other types without `relation` will throw the `OK\Dto\Exception\MapperInvalidTypeException`.

You can use any entity class as type, you just need to specify `relation` for it: `ManyToOne`, `OneToMany`, `ManyToMany`

Testing
-------

[](#testing)

```
composer install
vendor/bin/phpunit tests
```

Information
-----------

[](#information)

### Basic usage

[](#basic-usage)

All useful information will be retrieved from `Doctrine` annotations if `property` set or `type` is not set in `DTO` annotation.

```
@DTO(name="material")

@DTO(name="material_name", property="material")
```

### Using only simple types

[](#using-only-simple-types)

If you don't use `Doctrine\orm` you could use this mapper anyway.

Just create mapper without the second parameter and with you own `Reader` implementation if need.

```
new \OK\Dto\AnnotationMapper(new \Doctrine\Common\Annotations\AnnotationReader());
```

And then you can use only the simple types.

### Case sensitivity

[](#case-sensitivity)

You can use both `snake_case` and `camelCase` in `name` field and mapper will check both of variants in dataset if doesn't find the strict key. For example: If you have annotation:

```
@DTO(name="customerNumber", type="string")
```

and dataset:

```
$data = ['customer_number' => 123];
```

It's fine. At first mapper check the strict name `customerNumber`, then (if name doesn't exist) transforms name to `customer_number` and check it again. It works other way too (from `snake_case` to `camelCase`).

### Several naming

[](#several-naming)

If you need to have several names for one `Dto` annotation just list them via `|` delimiter and then you can use different name in data for different cases:

```
@DTO(name="customerNumber|userNumber|managerNumber", type="string")
```

If in dataset existed more then one from this set of names, then mapper will return first found.

### Using ManyToMany relation

[](#using-manytomany-relation)

For using `ManyToMany` relation you need to implement `OK\Dto\Repository\SearchCollectionInterface` for you entity repository or you can just extends from `OK\Dto\Repository\EntityRepository`

### Using OneToMany relation

[](#using-onetomany-relation)

Here are two ways to use this relation:

The first one when related entity existed then you need to pass array of id to dataset:

```
$data = ['customers' => [1,2,3]];
```

Another way when you need to create new Entity, then you need to pass data to create:

```
$data = ['customers' => [['firstName' => 'John', 'lastName' => 'Smith']]];
```

You can combine both this way in one dataset:

```
$data = ['customers' => [1, 2, ['firstName' => 'John', 'lastName' => 'Smith']];
```

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

29

—

LowBetter than 60% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity18

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~16 days

Recently: every ~31 days

Total

9

Last Release

1755d ago

Major Versions

1.5 → 2.02021-03-18

### Community

Maintainers

![](https://www.gravatar.com/avatar/30c891365dc8fb30fbe087883fddaa4163dfcbb7fd34b2e8f1c9c388d013fdb3?d=identicon)[GitHubHubus](/maintainers/GitHubHubus)

---

Top Contributors

[![GitHubHubus](https://avatars.githubusercontent.com/u/11797167?v=4)](https://github.com/GitHubHubus "GitHubHubus (28 commits)")

---

Tags

apisymfonydoctrinemapperdtofilling data

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/ok-dto-annotation-mapper/health.svg)

```
[![Health](https://phpackages.com/badges/ok-dto-annotation-mapper/health.svg)](https://phpackages.com/packages/ok-dto-annotation-mapper)
```

###  Alternatives

[event4u/data-helpers

Framework-agnostic PHP library for data mapping, DTOs and utilities. Includes DataMapper, SimpleDto/LiteDto, DataAccessor/Mutator/Filter and helper classes (MathHelper, EnvHelper, etc.). Works with Laravel, Symfony/Doctrine or standalone PHP.

1421.5k](/packages/event4u-data-helpers)[ecodev/graphql-doctrine

Declare GraphQL types from Doctrine entities and attributes

102147.9k4](/packages/ecodev-graphql-doctrine)[rcsofttech/audit-trail-bundle

Enterprise-grade, high-performance Symfony audit trail bundle. Automatically track Doctrine entity changes with split-phase architecture, multiple transports (HTTP, Queue, Doctrine), and sensitive data masking.

1022.4k](/packages/rcsofttech-audit-trail-bundle)[ahmed-bhs/doctrine-doctor

Runtime analysis tool for Doctrine ORM integrated into Symfony Web Profiler. Unlike static linters, it analyzes actual query execution at runtime to detect performance bottlenecks, security vulnerabilities, and best practice violations during development with real execution context and data.

813.1k](/packages/ahmed-bhs-doctrine-doctor)[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.

3847.7k1](/packages/rekalogika-mapper)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
