PHPackages                             haskel/map-serializer - 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. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. haskel/map-serializer

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

haskel/map-serializer
=====================

Object Serializer by map

v0.1.2(5y ago)0231MITPHP

Since Aug 7Pushed 5y agoCompare

[ Source](https://github.com/haskel/map-serializer)[ Packagist](https://packagist.org/packages/haskel/map-serializer)[ RSS](/packages/haskel-map-serializer/feed)WikiDiscussions master Synced 3d ago

READMEChangelog (3)Dependencies (2)Versions (4)Used By (1)

Use different tiny and simple schemas to serialize your objects and other structs

[![Latest Stable Version](https://camo.githubusercontent.com/03174a50d9eb4679335875bc2abd1d5b06b6db41899c24027db12d065d886725/68747470733a2f2f706f7365722e707567782e6f72672f6861736b656c2f6d61702d73657269616c697a65722f762f737461626c65)](https://packagist.org/packages/haskel/map-serializer)[![License](https://camo.githubusercontent.com/fa7d5fcf2c84b580327af52da95dd751703af65f079dc3c5a0081beac0789718/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4e65772532304253442d626c75652e737667)](https://github.com/haskel/map-serializer/blob/master/license.md)

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

[](#installation)

```
composer require haskel/map-serializer
```

Example
-------

[](#example)

```
/** Define a class that you want to serialize */
class User
{
    private $id;
    private $name;
    private status = 0;
    private $role;
    private $phone;
    private $mail;
    private group;

    public function __construct($id, $name, $role)
    {
        $this->id = $id;
        $this->name = $name;
        $this->role = $role;
    }

    /**
     * ... Boring code with getters and setters ...
     */
}

/** Specify the schema */
$schema = [
    'id'     => 'int',
    'name'   => 'string',
    'status' => 'int',
    'role'   => 'string',
];
/** Add this schema definition, uniq schema name and class name to serializer */
$serializer->addSchema(User::class, 'default', $schema);

/** serialize some instance of the class */
$result = $serializer->serialize(new User('Alice', 'user'));
```

```
{
  id: 1,
  name: 'Alice',
  status: 0,
  role: 'user'
}
```

Usage
-----

[](#usage)

### Basic usage

[](#basic-usage)

Register different schemas for specific class. Use second argument of `serialize()` method to specify a schema.

```
use Haskel\MapSerializer\Serializer;

$serializer = new Serializer();

$schemas = [
    'default' => [
        'id'     => 'int',
        'name'   => 'string',
        'status' => 'int',
        'role'   => 'string',
    ],
    'short' => [
        'id'   => 'int',
        'name' => 'string',
    ]
];
foreach ($orderSchemas as $schemaName => $schema) {
    $serializer->addSchema(User::class, $schemaName, $schema);
}

$users = [
    new User(1, 'Alice'),
    new User(2, 'Bob'),
];
$result = $serializer->serialize($users, 'short');
```

```
[
  {
    id: 1,
    name: 'Alice'
  },
  {
    id: 2,
    name: 'Bob'
  }
]
```

### Nested objects

[](#nested-objects)

1. add schema with name
2. use this name to nest an object

```
use Haskel\MapSerializer\Serializer;

$serializer = new Serializer();

$userSchema = [
    'id'     => 'int',
    'name'   => 'string',
    'group'  => 'short',
];
$groupSchema = [
  'id'   => 'int',
  'name' => 'string',
];
$serializer->addSchema(User::class, 'default', $userSchema);
$serializer->addSchema(Group::class, 'short', $groupSchema);

$group = new Group('sales');
$user = new User('Alice');
$user->addToGroup($group);

$result = $serializer->serialize($user);
```

```
{
  id: 1,
  name: 'Alice',
  group: {
    id: 1,
    name: 'sales'
  }
}
```

Format you object as you really want
------------------------------------

[](#format-you-object-as-you-really-want)

Formatter is an object which define specific transformation rules for entity. Formatter should implement `Haskel\MapSerializer\Formatter` interface

Look at this example

```
interface Formatter
{
    public function format($value, $schemaName);
}

class DatetimeFormatter implements Formatter
{
    public function format($value, $schemaName)
    {
        if (!$value instanceof DateTime) {
            throw new FormatterException(sprintf('wrong value type'));
        }

        switch ($schemaName) {
            case 'default':
            case 'datetime':
            default:
                return $value->format("Y-m-d H:i:s");

            case 'date':
                return $value->format('Y-m-d');

            case 'time':
                return $value->format('H:i:s');
        }
    }
}
```

How it works

```
use Haskel\MapSerializer\Formatter\DatetimeFormatter;
use Haskel\MapSerializer\Serializer;

$serializer = new Serializer();
$serializer->addFormatter(new DatetimeFormatter());

$datetime = new DateTime('2015-10-21 12:00:00');
$serializer->format($datetime, 'date');
```

```
'2015-10-21'
```

How to accelerate extracting
----------------------------

[](#how-to-accelerate-extracting)

Extractors are autogenerated classes that help you to extract fields from an object of some class.
`ExtractorGenerator` generates classes those can extract fields fastly without using reflection and without analysing of class structure. It looks like that:

```
final class AppEntityUserExtractor extends \Haskel\MapSerializer\EntityExtractor\BaseExtractor
{
    /** @var \App\Entity\User */
    protected $entity;

    protected function extract()
    {
        return [
            "id" => $this->entity->getId(),
            "name" => $this->entity->getName(),
        ];
    }

    public function exists($fieldName)
    {
        if (count($this->fields) === 0) {
            $this->fields = $this->extract();
        }

        return array_key_exists($fieldName, $this->fields);
    }

    /**
     * @param $fieldName
     *
     * @return mixed
     */
    public function get($fieldName)
    {
        if (count($this->fields) === 0) {
            $this->fields = $this->extract();
        }

        return $this->fields[$fieldName];
    }
}
```

Extracting works automatically, but if you want to specify your own extractor it would be easy. Just implement an interface `\Haskel\MapSerializer\EntityExtractor\Extractor`.

```
namespace Haskel\MapSerializer\EntityExtractor;

interface Extractor
{
    public function get($fieldName);
    public function exists($fieldName);
}

class UserExtractor implements Extractor
{
    public function get($fieldName)
    {
        return 42;
    }

    public function exists($fieldName)
    {
        return true;
    }
}
```

And register it in your serializer for specific scheme

```
$schema = [
    'id'     => 'int',
    'name'   => 'string',
    'status' => 'int',
    'role'   => 'string',
];
$serializer->addSchema(User::class, 'default', $schema);
$serializer->addExtractor(User::class, 'default', UserExtractor::class);
$result = $serializer->serialize(new User('Alice'));
```

```
{
  id: 42,
  name: '42',
  status: 42,
  role: '42'
}
```

###  Health Score

23

—

LowBetter than 27% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity51

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

Total

3

Last Release

2036d ago

### Community

Maintainers

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

---

Top Contributors

[![haskel](https://avatars.githubusercontent.com/u/721087?v=4)](https://github.com/haskel "haskel (27 commits)")

---

Tags

formattermap-serializermapperphpserializationserializerserializer

### Embed Badge

![Health badge](/badges/haskel-map-serializer/health.svg)

```
[![Health](https://phpackages.com/badges/haskel-map-serializer/health.svg)](https://phpackages.com/packages/haskel-map-serializer)
```

###  Alternatives

[masterminds/html5

An HTML5 parser and serializer.

1.8k242.8M229](/packages/masterminds-html5)[goetas-webservices/xsd2php

Convert XSD (XML Schema) definitions into PHP classes and JMS metadata

2411.6M37](/packages/goetas-webservices-xsd2php)[goetas-webservices/xsd2php-runtime

Convert XSD (XML Schema) definitions into PHP classes

4910.9M36](/packages/goetas-webservices-xsd2php-runtime)[thunderer/serializard

Flexible serializer

2767.3k1](/packages/thunderer-serializard)[goetas/xsd2php-runtime

Convert XSD (XML Schema) definitions into PHP classes

493.3k](/packages/goetas-xsd2php-runtime)[opensoft/simple-serializer

Simple Serializer

1914.2k1](/packages/opensoft-simple-serializer)

PHPackages © 2026

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