PHPackages                             peekandpoke/slumber - 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. peekandpoke/slumber

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

peekandpoke/slumber
===================

Serialization through Annotations

v1.1.1(8y ago)18852BSD-3-ClausePHPPHP &gt;=7.1

Since May 16Pushed 7y ago1 watchersCompare

[ Source](https://github.com/PeekAndPoke/slumber)[ Packagist](https://packagist.org/packages/peekandpoke/slumber)[ RSS](/packages/peekandpoke-slumber/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (8)Versions (18)Used By (2)

[![Code Coverage](https://camo.githubusercontent.com/2cd25183e8498f3f829f0f83628bd32f21e16e63302e8cca2695edbdb60ef8bf/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f5065656b416e64506f6b652f736c756d6265722f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/PeekAndPoke/slumber/?branch=master)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/0870eddf2e4f78a2fd9df8a429b0387310afd1cb610c22bbe85c230a9fa5e1e7/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f5065656b416e64506f6b652f736c756d6265722f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/PeekAndPoke/slumber/?branch=master)[![Build Status](https://camo.githubusercontent.com/2087521d6350035c9b1907b736f5e580a01299d8d94ff45f58a5f2de785566c4/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f5065656b416e64506f6b652f736c756d6265722f6261646765732f6275696c642e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/PeekAndPoke/slumber/build-status/master)

Slumber
=======

[](#slumber)

What is Slumber? It is a tool for mapping data from objects to arrays and vice versa.

It gives you the possibility to easily map your domain model to JSON. Or to map from JSON to your domain model classes.

Slumber uses Doctrine Annotations. The annotations are used to mark which properties of your classes are to be mapped and in which way.

(PHP5.6 compatibility until v0.4.x)

Basic example
=============

[](#basic-example)

The "trademark" of the slumber annotated classes are annotations like these:

```
use PeekAndPoke\Component\Slumber\Annotation\Slumber;

class MyClass {

    /**
     * @Slumber\AsString()
     */
    private $name;

    /**
     * @Slumber\AsInteger()
     */
    private $age;

    /**
     * @Slumber\AsDecimal()
     */
    private $height;

    /**
     * @Slumber\AsObject(Address::class)
     */
    private $address;
}

echo json_encode($codec->slumber(new MyClass());
```

might output the following:

```
{
  "name": "Bart",
  "age": 10,
  "height": 1.10,
  "address": {
    "city": "Springfield",
    "country": "USA"
  }
}
```

Getting started
===============

[](#getting-started)

Array codec example
-------------------

[](#array-codec-example)

In order to get the ArrayCodec into our hands we have to set it up:

```
// we need an instance of a PSR-11 container (should be provided by the application)
$di = ...;

// we need a doctrine annotation reader (you should use caching, ideally APCU as cache)
$annotationReader = new AnnotationReader();

// SLUMBER: we need a configuration reader (you should wrap the reader with CachedEntityConfigLookUp for good performance)
$reader = new AnnotatedEntityConfigReader($di, $annotationReader, new ArrayCodecPropertyMarker2Mapper());

// SLUMBER: finally we get the codec
$codec = new ArrayCodec($reader);

// then use it for serializating objects into array data
$data = $codec->slumber(new Person());

// or use if for de-serializating array data back into objects
$person = $codec->awake($data, Person::class);
```

Mapping
=======

[](#mapping)

In order to fully control serialization and de-serialization there is a set of annotations that can be used.

Mapping scalars
---------------

[](#mapping-scalars)

You will find the implementation of all mappers [here](./src/Slumber/Annotation/Slumber)

### Slumber\\AsBool()

[](#slumberasbool)

Maps values from and to booleans.

```
class C {
  /**
   * @Slumber\AsBool()
   */
  private $val = true;
}
```

maps to

```
{
  "val": true
}
```

```
class C {
  /**
   * @Slumber\AsBool()
   */
  private $val = 0;
}
```

maps to

```
{
  "val": false
}
```

The same behaviour applys for the opposite direction. For more details on how the mapper works have a look [here](./src/Slumber/Core/Codec/Property/BoolMapper.php)

### Slumber\\AsDecimal()

[](#slumberasdecimal)

Maps values from and to floating point values.

```
class C {
  /**
   * @Slumber\AsDecimal()
   */
  private $val = 1.23;
}
```

maps to

```
{
  "val": 1.23
}
```

```
class C {
  /**
   * @Slumber\AsDecimal()
   */
  private $val = "abc";
}
```

maps to

```
{
  "val": 0
}
```

The same behaviour applys for the opposite direction. For more details on how the mapper works have a look [here](./src/Slumber/Core/Codec/Property/DecimalMapper.php)

### Slumber\\AsInteger()

[](#slumberasinteger)

Maps values from and to floating point values.

```
class C {
  /**
   * @Slumber\AsInteger()
   */
  private $val = 1.23;
}
```

maps to

```
{
  "val": 1
}
```

```
class C {
  /**
   * @Slumber\AsInteger()
   */
  private $val = "abc";
}
```

maps to

```
{
  "val": 0
}
```

The same behaviour applys for the opposite direction. For more details on how the mapper works have a look [here](./src/Slumber/Core/Codec/Property/IntegerMapper.php)

### Slumber\\AsIs()

[](#slumberasis)

Maps values from and to as they are.

```
class C {
  /**
   * @Slumber\AsAs()
   */
  private $val = 1.23;
}
```

maps to

```
{
  "val": 1.23
}
```

```
class C {
  /**
   * @Slumber\AsIs()
   */
  private $val = "abc";
}
```

maps to

```
{
  "val": "abc"
}
```

The same behaviour applys for the opposite direction. For more details on how the mapper works have a look [here](./src/Slumber/Core/Codec/Property/AsIsMapper.php)

### Slumber\\AsString()

[](#slumberasstring)

Maps values from and to floating point values.

```
class C {
  /**
   * @Slumber\AsString()
   */
  private $val = 1.23;
}
```

maps to

```
{
  "val": "1.23"
}
```

```
class C {
  /**
   * @Slumber\AsString()
   */
  private $val = "abc";
}
```

maps to

```
{
  "val": "abc"
}
```

The same behaviour applys for the opposite direction. For more details on how the mapper works have a look [here](./src/Slumber/Core/Codec/Property/StringMapper.php)

Mapping Nested Objects
----------------------

[](#mapping-nested-objects)

### Slumber\\AsObject()

[](#slumberasobject)

Maps from and to nested objects.

```
class B {
  /**
   * @Slumber\AsString()
   */
  private $name;
}

class C {
  /**
   * @Slumber\AsObject(B::class)
   */
  private $val = new B();   // syntax error ... new B() only for demonstration purposes
}
```

maps to

```
{
  "val": {
    "name": "..."
  }
}
```

```
class C {
  /**
   * @Slumber\AsString()
   */
  private $val = "abc";
}
```

maps to

```
{
  "val": null
}
```

The same behaviour applys for the opposite direction. For more details on how the mapper works have a look [here](./src/Slumber/Core/Codec/Property/ObjectMapper.php)

### Slumber\\AsEnum()

[](#slumberasenum)

Maps values from and to enum values.

For this to work we need an Enum class. For details on the Enums have a look at [here](https://github.com/PeekAndPoke/php-types/blob/master/src/Enumerated.php).

```
class Enum extends Enumerated {

    /** @var Enum */
    public static $ONE;
    /** @var Enum */
    public static $TWO;
}

Enum::init();
```

```
class C {
  /**
   * @Slumber\AsEnum(Enum::class)
   */
  private $val = Enum::$ONE;
}
```

maps to

```
{
  "val": "ONE"
}
```

```
class C {
  /**
   * @Slumber\AsEnum(Enum::class)
   */
  private $val = "abc";
}
```

maps to

```
{
  "val": null
}
```

The same behaviour applys for the opposite direction. For more details on how the mapper works have a look [here](./src/Slumber/Core/Codec/Property/EnumMapper.php)

Mapping Collections, Lists, KeyValue-Pairs
------------------------------------------

[](#mapping-collections-lists-keyvalue-pairs)

### Slumber\\AsList()

[](#slumberaslist)

Maps values from and to lists (arrays without indexes).

The annotations expects a nested annotation that controls the shape of the elements within the collection.

```
class C {
  /**
   * @Slumber\AsList(
   *   @Slumber\AsDecimal()
   * )
   */
  private $val = [1.1, 2.2, 3.3];
}
```

maps to

```
{
  "val": [1.1, 2.2, 3.3]
}
```

```
class C {
  /**
   * @Slumber\AsList(
   *   @Slumber\AsDecimal()
   * )
   */
  private $val = ["a": 1.1, "b": 2.2, "c": 3.3];
}
```

maps to

```
{
  "val": [1.1, 2.2, 3.3]
}
```

The same behaviour applys for the opposite direction. For more details on how the mapper works have a look [here](./src/Slumber/Core/Codec/Property/ListMapper.php)

Similarly one would map to a list of objects:

```
class B { }

class C {

  /**
   * @Slumber\AsList(
   *   @Slumber\AsObject(B::Class)
   * )
   */
  private $val = [];
}
```

### Slumber\\AsMap()

[](#slumberasmap)

Maps values from and to KeyValue-Pairs (arrays with indexes).

The annotations expects a nested annotation that controls the shape of the elements within the collection.

```
class C {
  /**
   * @Slumber\AsMap(
   *   @Slumber\AsDecimal()
   * )
   */
  private $val = [1.1, 2.2, 3.3];
}
```

maps to

```
{
  "val": { "0": 1.1, "1": 2.2, "2": 3.3 }
}
```

```
class C {
  /**
   * @Slumber\AsList(
   *   @Slumber\AsDecimal()
   * )
   */
  private $val = ["a": 1.1, "b": 2.2, "c": 3.3];
}
```

maps to

```
{
  "val": { "a": 1.1, "b": 2.2, "c": 3.3}
}
```

The same behaviour applys for the opposite direction. For more details on how the mapper works have a look [here](./src/Slumber/Core/Codec/Property/MapMapper.php)

Similarly one would map to a list of objects:

```
class B { }

class C {

  /**
   * @Slumber\AsMap(
   *   @Slumber\AsObject(B::Class)
   * )
   */
  private $val = [];
}
```

### Slumber\\AsKeyValuePairs()

[](#slumberaskeyvaluepairs)

Maps values from and to special shaped KeyValue-Pairs. This can be useful in terms of database indexing.

The annotations expects a nested annotation that controls the shape of the elements within the collection.

```
class C {
  /**
   * @Slumber\AsMap(
   *   @Slumber\AsDecimal()
   * )
   */
  private $val = [1.1, 2.2, 3.3];
}
```

maps to

```
{
  "val": [
    { "k": "0", "v": 1.1 },
    { "k": "1", "v": 2.2 },
    { "k": "2", "v": 3.3 }
  ]
}
```

```
class C {
  /**
   * @Slumber\AsList(
   *   @Slumber\AsDecimal()
   * )
   */
  private $val = ["a": 1.1, "b": 2.2, "c": 3.3];
}
```

maps to

```
{
  "val": [
    { "k": "a", "v": 1.1 },
    { "k": "b", "v": 2.2 },
    { "k": "c", "v": 3.3 }
  ]
}
```

The same behaviour applys for the opposite direction. For more details on how the mapper works have a look [here](./src/Slumber/Core/Codec/Property/KeyValuePairsMapper.php)

Similarly one would map to a list of objects:

```
class B { }

class C {

  /**
   * @Slumber\AsKeyValuePairs(
   *   @Slumber\AsObject(B::Class)
   * )
   */
  private $val = [];
}
```

Polymorphism example
--------------------

[](#polymorphism-example)

When serializing the polymorphism information is not needed. Since we know exactly which class we have in our hand to serialize.

But while de-serialization polymorphism needs to be annotated explicitly. Only by doing this we can know which classes to instantiate. We also need a field in the data, which acts as the discriminator.

```
use PeekAndPoke\Component\Slumber\Annotation\Slumber;

/*
 * @Slumber\Polymorphic(
 *     {
 *         "adyen"  : Adyen::class,
 *         "paypal" : Paypal::class,
 *         "stripe" : Stripe::class,
 *     },
 *     tellBy  = "provider",
 *     default = PaymentMean::class
 * )
 */
class PaymentMean {

  /**
   * The discriminator field
   *
   * @Slumber\AsString()
   */
  private $provider;

  /* ... */
}

class Adyen extends PaymentMean {

  /* ... */
}

class Paypal extends PaymentMean {

  /* ... */
}

class Stripe extends PaymentMean {

  /* ... */
}
```

TICKETS:
========

[](#tickets)

next ticket number: 14

PRIO I
------

[](#prio-i)

SLUMBER-13 - 0%
( ) unit test for polymorphics that fall back to the default
( ) a) discriminator no set
( ) b) unknown discriminator set

SLUMBER-12 - 50% - Implement aliases class for repositories -&gt; in order to store multiple type in one collection we must be able to specify alias classes for repositories (x) reported 2016-11-15 (x) implemented 2016-11-15 ( ) unit-tests

SLUMBER-4 - 0% - Refactor the hardcoded visitors in the MongoDbCodec set to come from the MongoDbEntityConfig -&gt; the config reader must automatically add the visitors (can user override these somehow?) -&gt; it is more generic and will work fine in conjunction with user-attached listeners
(x) reported 2016-05-01

SLUMBER-7 - 0% -

PRIO II
-------

[](#prio-ii)

SLUMBER-3 - 0% - Let visitors like onPreCreate() pass an event class instead of multiple parameters -&gt; better extensibility -&gt; event propagation could be stopped (x) reported 2016-05-01

SLUMBER-2 - 0% - setting and reading of properties through getters and setters first. If not possible use reflection
-&gt; reading and writing of inherited private properties will be possible
-&gt; +33% speed
(x) reported 2016-05-01

SLUMBER-8 - 0% - implement GeoJSON support for Data\\MongoDB
-&gt; implement GeoSpatialIndex for GeoJson types -&gt; implement GeoJsonPolygon, GeoJsonMultiPolygon and other GeoJson types (x) reported 2016-05-12

SLUMBER-7 - IRepository::save should return a more specific result than @return array|null (x) reported 2016-05-12

PRIO III
--------

[](#prio-iii)

SLUMBER-6 - 0% - Make Slumber\\Swagger an own package and base it on a generic code generation component -&gt; this is a project of its own -&gt; get rid of gossi/php-code-gen (x) reported 2016-05-01

Completed
---------

[](#completed)

SLUMBER-1 - 100% - Remove @AsOne2One annotation and do similar as with @AsId -&gt; currently entities marked like this cannot be used with the ArrayCodec (which is broken behaviour) (x) completed 2016-05-11

SLUMBER-5 - 100% - move Slumber\\MongoDb to Slumber\\Data\\MongoDb -&gt; Slumber\\Data will be the home of all database things (x) completed 2016-05-11

SLUMBER-9 - 100% - implement polymorphic slumbering and awaking (x) reported 2016-05-14 (x) completed 2016-10-01 (x) unit-tests

SLUMBER-10 - 100% implement usage of collection classes for all AsCollection mappings -&gt; This will make it possible to wrap incoming arrays into Collection classes. -&gt; This will increase convenience for operations on array since the code will be encapsulated alongside the data -&gt; Example: a TagsSet collection type which contains tags, could have methods like has(), addUnique(), remove() (x) reported 2016-11-01 (x) completed 2016-11-13 (x) unit-tests

SLUMBER-11 - 100% implement LazyDbRefCollection for storing lists of referenced objects (x) reported 2016-11-13 (x) completed 2016-11-13 (x) unit-tests

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity15

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity67

Established project with proven stability

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

Total

17

Last Release

2994d ago

Major Versions

v0.6.1 → v1.0.02018-02-16

PHP version history (3 changes)v0.2.0PHP ^7.1

v0.3.0PHP &gt;=5.6

v0.5.1PHP &gt;=7.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/82d9145b8f142b52aa21e66cddb1e493e4f6dbcd0629f6a65204260e890dca5c?d=identicon)[PeekAndPoke](/maintainers/PeekAndPoke)

---

Top Contributors

[![PeekAndPoke](https://avatars.githubusercontent.com/u/753129?v=4)](https://github.com/PeekAndPoke "PeekAndPoke (118 commits)")

---

Tags

codecdeserializationserialization

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/peekandpoke-slumber/health.svg)

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

###  Alternatives

[laravel/framework

The Laravel Framework.

34.6k509.9M17.0k](/packages/laravel-framework)[sylius/sylius

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

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

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

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

EC-CUBE EC open platform.

78527.0k1](/packages/ec-cube-ec-cube)[drupal/core-recommended

Locked core dependencies; require this project INSTEAD OF drupal/core.

6939.5M341](/packages/drupal-core-recommended)[civicrm/civicrm-core

Open source constituent relationship management for non-profits, NGOs and advocacy organizations.

728272.9k17](/packages/civicrm-civicrm-core)

PHPackages © 2026

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