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

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

guennichi/mapper
================

A lightweight library to map array data to PHP immutable objects

2.1.3(1y ago)1213.3k↓34.6%1MITPHPPHP ^8.1CI failing

Since Sep 12Pushed 3mo ago1 watchersCompare

[ Source](https://github.com/rguennichi/mapper)[ Packagist](https://packagist.org/packages/guennichi/mapper)[ RSS](/packages/guennichi-mapper/feed)WikiDiscussions 2.0 Synced 1mo ago

READMEChangelog (10)Dependencies (11)Versions (17)Used By (0)

Mapper: Map arrays into PHP objects and collections
===================================================

[](#mapper-map-arrays-into-php-objects-and-collections)

A lightweight, high-performance PHP library that maps array data into **immutable objects, collections, and strongly typed arrays** via constructors. Perfect for transforming API responses, JSON data, or any array structure into type-safe PHP objects.

Why Use Mapper?
---------------

[](#why-use-mapper)

- **🚀 Fast**: Up to 7x faster than Symfony Serializer (see benchmarks below)
- **🔒 Type-safe**: Leverages PHP 8.1+ type system and PHPDoc annotations
- **📦 Immutable**: Works with readonly properties for immutable objects
- **🎯 Simple**: Map arrays to objects using constructor parameters - no setters needed
- **⚡ Production-ready**: Built-in caching for optimal performance

Benchmark
---------

[](#benchmark)

BenchmarkRevsItsmem\_peakModerstdev`unserialize()`500051.724mb9.547μs±1.51%`symfony/serializer`500053.489mb122.343μs±0.84%`guennichi/mapper`50005**2.972mb****16.638μs****±0.41%**Check `benchmark/` directory for more details about the implementation.

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

[](#installation)

```
composer require guennichi/mapper
```

**Requirements:** PHP ^8.1

Quick Start
-----------

[](#quick-start)

```
use Guennichi\Mapper\Mapper;
use Guennichi\Mapper\Metadata\ConstructorFetcher;
use Guennichi\Mapper\Metadata\Factory\ArgumentFactory;
use Guennichi\Mapper\Metadata\Factory\ArgumentTypeFactory;
use Guennichi\Mapper\Metadata\Factory\ConstructorFactory;
use Guennichi\Mapper\Metadata\Factory\PhpDocumentorArgumentTypeFactory;
use Guennichi\Mapper\Metadata\Factory\ReflectionArgumentTypeFactory;
use Guennichi\Mapper\Metadata\Repository\InMemoryConstructorRepository;

// Create the mapper
$mapper = new Mapper(
    new ConstructorFetcher(
        new ConstructorFactory(
            new ArgumentFactory(
                new ArgumentTypeFactory(
                    new PhpDocumentorArgumentTypeFactory(),
                    new ReflectionArgumentTypeFactory(),
                ),
            ),
        ),
        new InMemoryConstructorRepository(),
    ),
);

// Define your class
final class Product
{
    public function __construct(
        public readonly string $name,
        public readonly float $price,
    ) {}
}

// Map array to object
$data = ['name' => 'Laptop', 'price' => 999.99];
$product = $mapper($data, Product::class);
```

Real-World Example: API Response Mapping
----------------------------------------

[](#real-world-example-api-response-mapping)

Transform API responses into strongly-typed objects:

```
use Guennichi\Mapper\Attribute\DateTimeFormat;
use Guennichi\Mapper\Attribute\Flexible;
use Guennichi\Mapper\Attribute\Name;

final class ApiProduct
{
    public function __construct(
        #[Name('productName')] // Map 'productName' to $name
        public readonly string $name,
        #[Flexible] // Convert 'yes'/'no' to boolean
        public readonly bool $active,
        #[DateTimeFormat('Y-m-d')] // Custom date format
        public readonly \DateTimeInterface $createdAt,
    ) {}
}

$apiResponse = [
    'productName' => 'Gaming Laptop',
    'active' => 'yes', // Converted to true
    'createdAt' => '2023-02-10',
];

$product = $mapper($apiResponse, ApiProduct::class);
```

See [docs/USAGE.md](docs/USAGE.md) for complete examples with nested objects, collections, and more.

Migration from `serialize()` / `unserialize()`
----------------------------------------------

[](#migration-from-serialize--unserialize)

**Before:**

```
$serialized = serialize($product);
$product = unserialize($serialized);
```

**After:**

```
$data = json_encode(['name' => $product->name, 'price' => $product->price]);
$product = $mapper(json_decode($data, true), Product::class);
```

**Benefits:** Type-safe, works with immutable objects, safe with untrusted data, human-readable JSON.

See [docs/USAGE.md](docs/USAGE.md) for detailed migration guide.

Features
--------

[](#features)

- ✅ Map arrays to objects via constructors
- ✅ Support for collections, nested objects, enums, DateTime
- ✅ Custom attributes for field mapping, type coercion, date formats
- ✅ Built-in caching for production performance
- ✅ Full type validation and error handling

Documentation
-------------

[](#documentation)

📖 **[Complete Usage Guide](docs/USAGE.md)** - Comprehensive documentation covering:

- Configuration &amp; setup (development and production)
- Collections and nested objects
- Complete type system reference
- All attributes with examples
- Performance optimization
- Error handling and troubleshooting
- Best practices

License
-------

[](#license)

MIT

Credits
-------

[](#credits)

Special thanks to [@Gabriel Ostrolucký](https://github.com/ostrolucky) for his support and advice to make this happen.

###  Health Score

47

—

FairBetter than 94% of packages

Maintenance65

Regular maintenance activity

Popularity32

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity64

Established project with proven stability

 Bus Factor1

Top contributor holds 80.8% 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 ~82 days

Recently: every ~222 days

Total

16

Last Release

111d ago

Major Versions

1.0.x-dev → 2.0.02023-04-01

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/287419?v=4)[Radhi](/maintainers/Radhi)[@radhi](https://github.com/radhi)

---

Top Contributors

[![rguennichi](https://avatars.githubusercontent.com/u/88873441?v=4)](https://github.com/rguennichi "rguennichi (21 commits)")[![ostrolucky](https://avatars.githubusercontent.com/u/496233?v=4)](https://github.com/ostrolucky "ostrolucky (3 commits)")[![victormech](https://avatars.githubusercontent.com/u/685345?v=4)](https://github.com/victormech "victormech (2 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/guennichi-mapper/health.svg)

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

###  Alternatives

[symplify/monorepo-builder

Not only Composer tools to build a Monorepo.

5205.3M82](/packages/symplify-monorepo-builder)[cognesy/instructor-php

The complete AI toolkit for PHP: unified LLM API, structured outputs, agents, and coding agent control

310107.9k1](/packages/cognesy-instructor-php)[symfony/ai-platform

PHP library for interacting with AI platform provider.

51927.7k136](/packages/symfony-ai-platform)[phuml/phuml

phUML is a fully automatic UML class diagram generator for PHP code

11411.3k1](/packages/phuml-phuml)[numero2/contao-storelocator

Contao Plugin for managing stores (or in common address data) and providing a frontend-search based on geo data

121.5k](/packages/numero2-contao-storelocator)

PHPackages © 2026

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