PHPackages                             philiprehberger/php-dto-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. philiprehberger/php-dto-mapper

ActiveLibrary

philiprehberger/php-dto-mapper
==============================

Map arrays and JSON to strongly-typed DTOs with attribute-driven configuration

v1.0.3(1mo ago)11[1 PRs](https://github.com/philiprehberger/php-dto-mapper/pulls)MITPHPPHP ^8.2CI passing

Since Mar 15Pushed 1mo agoCompare

[ Source](https://github.com/philiprehberger/php-dto-mapper)[ Packagist](https://packagist.org/packages/philiprehberger/php-dto-mapper)[ Docs](https://github.com/philiprehberger/php-dto-mapper)[ RSS](/packages/philiprehberger-php-dto-mapper/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (3)Versions (5)Used By (0)

PHP DTO Mapper
==============

[](#php-dto-mapper)

[![Tests](https://github.com/philiprehberger/php-dto-mapper/actions/workflows/tests.yml/badge.svg)](https://github.com/philiprehberger/php-dto-mapper/actions/workflows/tests.yml)[![Latest Version on Packagist](https://camo.githubusercontent.com/4b4b0a2025b26d7a29a380a679ce8f1ba835f31965a2484b0bcb788869b99153/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7068696c69707265686265726765722f7068702d64746f2d6d61707065722e737667)](https://packagist.org/packages/philiprehberger/php-dto-mapper)[![License](https://camo.githubusercontent.com/94713e477c369227bfff305940915d30006bdfa61bab054186053debb9f70b4a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f7068696c69707265686265726765722f7068702d64746f2d6d6170706572)](LICENSE)

Map arrays and JSON to strongly-typed DTOs with attribute-driven configuration.

---

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

[](#requirements)

DependencyVersionPHP^8.2Zero external dependencies.

---

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

[](#installation)

```
composer require philiprehberger/php-dto-mapper
```

---

Usage
-----

[](#usage)

### Define a DTO

[](#define-a-dto)

```
use PhilipRehberger\DtoMapper\Attributes\MapFrom;
use PhilipRehberger\DtoMapper\Attributes\Optional;
use PhilipRehberger\DtoMapper\Attributes\CastWith;
use PhilipRehberger\DtoMapper\Casters\DateTimeCaster;

class UserDto
{
    public function __construct(
        public readonly string $name,
        #[MapFrom('email_address')]
        public readonly string $email,
        #[Optional]
        public readonly ?string $nickname = null,
        #[CastWith(DateTimeCaster::class)]
        public readonly ?\DateTimeImmutable $createdAt = null,
    ) {}
}
```

### Map from array

[](#map-from-array)

```
use PhilipRehberger\DtoMapper\DtoMapper;

$dto = DtoMapper::map([
    'name' => 'John',
    'email_address' => 'john@example.com',
    'createdAt' => '2026-01-15 10:30:00',
], UserDto::class);

$dto->name;      // 'John'
$dto->email;     // 'john@example.com'
$dto->createdAt; // DateTimeImmutable
```

### Map from JSON

[](#map-from-json)

```
$dto = DtoMapper::mapJson('{"name": "Jane", "email_address": "jane@example.com"}', UserDto::class);
```

### Map a collection

[](#map-a-collection)

```
$dtos = DtoMapper::mapCollection([
    ['name' => 'Alice', 'email_address' => 'alice@example.com'],
    ['name' => 'Bob', 'email_address' => 'bob@example.com'],
], UserDto::class);
```

### Safe mapping

[](#safe-mapping)

```
$dto = DtoMapper::tryMap($data, UserDto::class); // Returns null on failure
```

### Nested DTOs

[](#nested-dtos)

```
class AddressDto
{
    public function __construct(
        public readonly string $street,
        public readonly string $city,
    ) {}
}

class PersonDto
{
    public function __construct(
        public readonly string $name,
        public readonly AddressDto $address,
    ) {}
}

$dto = DtoMapper::map([
    'name' => 'Alice',
    'address' => ['street' => '123 Main St', 'city' => 'Springfield'],
], PersonDto::class);

$dto->address->city; // 'Springfield'
```

### Custom casters

[](#custom-casters)

Implement the `Caster` interface:

```
use PhilipRehberger\DtoMapper\Contracts\Caster;

class MoneyFromCentsCaster implements Caster
{
    public function cast(mixed $value): float
    {
        return (int) $value / 100;
    }
}
```

Use with the `#[CastWith]` attribute:

```
class OrderDto
{
    public function __construct(
        #[CastWith(MoneyFromCentsCaster::class)]
        public readonly float $total,
    ) {}
}
```

### Enum casting

[](#enum-casting)

```
use PhilipRehberger\DtoMapper\Attributes\CastWith;
use PhilipRehberger\DtoMapper\Casters\EnumCaster;

enum Status: string
{
    case Active = 'active';
    case Inactive = 'inactive';
}

class AccountDto
{
    public function __construct(
        public readonly string $name,
        #[CastWith(EnumCaster::class, args: [Status::class])]
        public readonly Status $status,
    ) {}
}
```

---

API
---

[](#api)

MethodDescription`DtoMapper::map(array $data, string $class): object`Map an associative array to a DTO`DtoMapper::mapJson(string $json, string $class): object`Map a JSON string to a DTO`DtoMapper::mapCollection(array $items, string $class): array`Map an array of arrays to DTOs`DtoMapper::tryMap(array $data, string $class): ?object`Map returning null on failure### Attributes

[](#attributes)

AttributeTargetDescription`#[MapFrom('key')]`PropertyMap from a different source key`#[Optional]`PropertyAllow missing keys, use default value`#[CastWith(Caster::class)]`PropertyApply a custom caster### Built-in Casters

[](#built-in-casters)

CasterDescription`DateTimeCaster`Casts string to `DateTimeImmutable``EnumCaster`Casts string/int to a backed enum---

Development
-----------

[](#development)

```
composer install
vendor/bin/phpunit
vendor/bin/pint --test
vendor/bin/phpstan analyse
```

License
-------

[](#license)

MIT

###  Health Score

39

—

LowBetter than 86% of packages

Maintenance89

Actively maintained with recent releases

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity49

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

Total

4

Last Release

56d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/cfd7d24cbbf32400fa13ce0bbe7a31edd2d66a6d4488eafdb3d64c5337bf0435?d=identicon)[philiprehberger](/maintainers/philiprehberger)

---

Top Contributors

[![philiprehberger](https://avatars.githubusercontent.com/u/8218077?v=4)](https://github.com/philiprehberger "philiprehberger (5 commits)")

---

Tags

mapperdtocastinghydrationdata-transfer

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/philiprehberger-php-dto-mapper/health.svg)

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

###  Alternatives

[eventsauce/object-hydrator

Converts structured data into strict objects.

3322.3M20](/packages/eventsauce-object-hydrator)[brick/json-mapper

Maps JSON data to strongly typed PHP DTOs

20552.1k3](/packages/brick-json-mapper)[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)[idr0id/papper

Papper is PHP convention-based object to object mapper

4927.0k1](/packages/idr0id-papper)[nutgram/hydrator

Hydrator for PHP 8.0+

12265.2k6](/packages/nutgram-hydrator)[artyuum/request-dto-mapper-bundle

This bundle provides an easy way to automatically map the incoming request data to a DTO and optionally validate it.

515.8k](/packages/artyuum-request-dto-mapper-bundle)

PHPackages © 2026

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