PHPackages                             ehyiah/mapping-bundle - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. ehyiah/mapping-bundle

ActiveSymfony-bundle[Utility &amp; Helpers](/categories/utility)

ehyiah/mapping-bundle
=====================

Symfony Bundle to easily map Objects into each other

0.4.4(1y ago)35.0k↓51.9%1[1 issues](https://github.com/Ehyiah/MappingBundle/issues)1MITPHPPHP &gt;=8.1CI passing

Since Feb 6Pushed 1y ago1 watchersCompare

[ Source](https://github.com/Ehyiah/MappingBundle)[ Packagist](https://packagist.org/packages/ehyiah/mapping-bundle)[ RSS](/packages/ehyiah-mapping-bundle/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (13)Versions (23)Used By (1)

MappingBundle
=============

[](#mappingbundle)

Symfony bundle to automap an object into another object easily.

It was mainly built in order to avoid passing full entities to symfony forms when you want to edit them. But you can use it in many ways.

It was designed to be as easy as possible, all the mapping is located into a single object that is "aware" of the target class and properties destinations. There is no configuration outside of the main object.

The main service have two methods :

- mapToTarget : This method will map the mapped Aware object to a target object. The target object can be another simple object or an entity. e.g : You have a form with a data\_class that is an object that will represent some properties of an entity, for a User for example.
- mapFromTarget : this method will do the opposite. It will take an object (or an entity that is tagged as the target) and map properties into the mapped Aware object.

Installation
============

[](#installation)

Make sure Composer is installed globally, as explained in the [installation chapter](https://getcomposer.org/doc/00-intro.md)of the Composer documentation.

Applications that use Symfony Flex
----------------------------------

[](#applications-that-use-symfony-flex)

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

```
$ composer require ehyiah/mapping-bundle
```

Applications that don't use Symfony Flex
----------------------------------------

[](#applications-that-dont-use-symfony-flex)

### Step 1: Download the Bundle

[](#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 ehyiah/mapping-bundle
```

### Step 2: Enable the Bundle

[](#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:

```
// config/bundles.php

return [
    // ...
    \\::class => ['all' => true],
];
```

Usage
=====

[](#usage)

In order to use this bundle, you will need to mark an object (basically a DTO) with the attribute Ehyiah\\MappingBundle\\Attributes\\MappingAware

And in the same class, simply tag every properties you want to map to the target object with the same attribute. If the properties in the target class and the mapped DTO have the same name, there is nothing else to do (see `$text` property example). If the properties have a different name, you can use the `target` option to specify the name in the target class.

As the mapping logic is using the propertyAccess component, you can specify nested properties in the target class. see `zipcode` and `street` properties in the example below.

If you want to ignore `null` values when mapping from an object to the other, juste use the `ignoreNullValue` option on each properties you need to.

Simple Usage
------------

[](#simple-usage)

1 - Create a DTO that will 'hold' the mapping logic

```
    // src/DTO/MyAwesomeDTO

    use App\src\Entity;
    use Ehyiah\MappingBundle\Attributes;

    #[MappingAware(target: MyAwesomeEntity::class)]
    class MyAwesomeDTO
    {
        #[MappingAware]
        public string $text

        #[MappingAware(target: 'aBooleanProperty')]
        public bool $active

        #[MappingAware(target: 'address.zipcode')]
        public bool $zipcode

        #[MappingAware(target: 'address.street')]
        public bool $street
    }
```

2 - Inject the `MappingServiceInterface` into your code, and call the methods.

```
    use App\src\Entity\MyAwesomeEntity;
    use App\src\DTO\MyAwesomeDTO;
    use Ehyiah\MappingBundle\Attributes;
    use Ehyiah\MappingBundle\MappingServiceInterface;

    class SomeUsefulServiceOrHandlerOrController
    {
        public function __construct(
            private MappingServiceInterface $mappingService,
        ) {
        }

        public function handle()
        {
            $entity = new MyAwesomeEntity();
            $dto = new MyAwesomeDTO();

            $this->mappingService->mapToTarget($dto, $entity);
            $this->mappingService->mapFromTarget($entity, $dto);
        }
    }
```

If you call `mapToTarget()` function of the service tagged with `MappingServiceInterface` in a controller, handler or wherever you need it, the service will take properties tagged with MappingAware attribute and will put the values stored in the DTO into the properties in the entity and flush them (default value).

Advanced usage
==============

[](#advanced-usage)

Replace the Built-in service
----------------------------

[](#replace-the-built-in-service)

A Default service implementing `MappingServiceInterface` exist in the bundle. But you may need to create a service that implements the `MappingServiceInterface` to replace the default built-in.

### Create your own service

[](#create-your-own-service)

To create your own service :

- Just create a service that implements the `MappingServiceInterface`, there is nothing more to do, no need to register or override the default built-in. The compiler pass do the work for you.
- In this service you will handle the logic yourself.
- Of course you can take the basis methods of the default service and modify them to your needs inside your custom service.

Transformers
------------

[](#transformers)

Sometimes you need to modify data between the objects.

Example : in your SourceObject you have a string and need a Datetime in the TargetObject. Or the opposite

Well there is a simple way to do this via Transformers. You can easily create them or use some of prebuilt. To create them just create a class and implements `TransformerInterface`

Transformers will have 2 methods `transform` and `reverseTransform`. and you can pass an array of options that will be used in both.

`transform` method is used in mapToTarget

`reverseTransform` method is used in mapFromTarget

In each method you have access ot the SourceObject and the TargetObject.

```
    // src/DTO/MySourceObject

    use Ehyiah\MappingBundle\Attributes;

    #[MappingAware(target: MyTargetObject::class)]
    class MySourceObject
    {
        #[MappingAware(transformer: \Ehyiah\MappingBundle\Transformer\DateTimeTransformer::class, options: ['option1' => 'value1'])]
        public string $date
    }
```

```
    // src/DTO/MyTargetObject

    class MyTargetObject
    {
        public DateTime $date
    }
```

Going Further with Transformers
-------------------------------

[](#going-further-with-transformers)

Transformers can be "open-minded" or "narrow-minded". For a better understanding there is an easy-to-understand example built-in with `StringToDateTimeTransformer` and `DateTimeTransformer`.

Which one to choose is entirely to your mind ! The only difference between them is how you code the transform and reverseTransform methods.

### Narrow-minded transformers

[](#narrow-minded-transformers)

If you pick as examples the `StringToDateTimeTransformer` : It is said as a narrow-minded transformer as it will only accept to transform String to DateTime and reverseTransform DateTime to String. It will pick a string from the sourceObject and transform it into a DateTime object in the target object (via the mapToTarget method). And will pick the DateTime object from the target object and reverseTransform it into the sourceObject (via the mapFromTarget method)

If you try to do the opposite an Exception will be thrown.

### Open-minded transformers

[](#open-minded-transformers)

If you pick as examples the `DateTimeTransformer` : It is said as an open-minded transformer as it will accept :

- to transform String to DateTime and reverseTransform DateTime to String.
- but also to transform Datetime to String and reverseTransform String to Datetime.

List Of built-in Transformers
-----------------------------

[](#list-of-built-in-transformers)

### Open-minded :

[](#open-minded-)

Transformertransform and reverseTransformoptionsDateTimeTransformerstring to DateTime OR DateTime to string`format` (use to transform the string with the provided format)
 example `'format' => 'Y/m/d'`
 `timezone` a valid DateTimeZone object example : `'timezone' => new DateTimeZone('UTC')`BooleanTransformerstring|int to boolean OR boolean to string|int`trueValue` or `falseValue` example: `'trueValue' => 'MyCustomTrueValue'`

 `strict` : true or falseEnumTransformerEnum|Enum\[\] into string|string\[\] OR string|string\[\] to enum|enum\[\]`enum` the class of the enum example : `'enum' => MyEnum::class`### Narrow-minded:

[](#narrow-minded)

Transformertransformtransform available optionsreverseTransformreverseTransform available optionsStringToDateTimeTransformerstring to DateTime`timezone` a valid DateTimeZone object example : `'timezone' => new DateTimeZone('UTC')`DateTime to string`format` (use to transform the string with the provided format)
 example `'format' => 'Y/m/d'`StringToBooleanTransformerstring to Boolean`strict` : true or falseBoolean to string`trueValue` or `falseValue` example: `'trueValue' => 'MyCustomTrueValue'`StringToEnumTransformerstring or array of strings to enum or array of enum`enum` the class of the enum example : `'enum' => MyEnum::class`enum or array of enum to string or array of strings`enum` the class of the enum example : `'enum' => MyEnum::class`
 `return` in case you would need to return the NAME instead of the VALUE example: `return => StringToEnumTransformer::RETURN_NAME `CollectionTransformercollection of object to collection of object`targetClass` the expected class for elements in the collection (mandatory), `fillFrom` the collection property from where you would load data to simulate `clearMissing = false`collection of object to collection of object`sourceClass` the current class of elements in the collection (mandatory)### Mapped collection inside Mapped object

[](#mapped-collection-inside-mapped-object)

If you need to have sub mapped elements inside your initial mapped class, the `CollectionTransformer` is the perfect fit.

- it can allow you to map collection elements to another (or also same to benefit of other `CollectionTransformer` feature!) class
- it can simulate the clearMissing feature to avoid default mapping clear on element not posted
- it can be deep chained

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance36

Infrequent updates — may be unmaintained

Popularity27

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity50

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 ~17 days

Recently: every ~59 days

Total

22

Last Release

469d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/20b949075ead003842634930b14d05c29409404dd20e50d8aa427c87ad3e8d40?d=identicon)[Ehyiah](/maintainers/Ehyiah)

---

Top Contributors

[![Ehyiah](https://avatars.githubusercontent.com/u/22179288?v=4)](https://github.com/Ehyiah "Ehyiah (94 commits)")

---

Tags

mappermappingsymfonysymfony-bundlesymfonymapping

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/ehyiah-mapping-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/ehyiah-mapping-bundle/health.svg)](https://phpackages.com/packages/ehyiah-mapping-bundle)
```

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M651](/packages/sylius-sylius)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)[prestashop/prestashop

PrestaShop is an Open Source e-commerce platform, committed to providing the best shopping cart experience for both merchants and customers.

9.0k15.4k](/packages/prestashop-prestashop)[ec-cube/ec-cube

EC-CUBE EC open platform.

78527.0k1](/packages/ec-cube-ec-cube)[open-dxp/opendxp

Content &amp; Product Management Framework (CMS/PIM)

7310.3k29](/packages/open-dxp-opendxp)[2lenet/crudit-bundle

The easy like Crud'it Bundle.

1714.8k8](/packages/2lenet-crudit-bundle)

PHPackages © 2026

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