PHPackages                             aternos/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. aternos/serializer

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

aternos/serializer
==================

A PHP library for (de-)serialization using attributes and reflection

1.4.0(9mo ago)13.8k↓38.4%1MITPHPPHP &gt;=8.2CI passing

Since Oct 2Pushed 9mo ago2 watchersCompare

[ Source](https://github.com/aternosorg/php-serializer)[ Packagist](https://packagist.org/packages/aternos/serializer)[ RSS](/packages/aternos-serializer/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (6)Dependencies (1)Versions (7)Used By (0)

aternos/serializer
==================

[](#aternosserializer)

A PHP library for (de-)serialization using attributes and reflection.

- [Installation](#installation)
- [Usage](#usage)
- [The Serialize Attribute](#the-serialize-attribute)
    - [Name](#name)
    - [Required](#required)
    - [Allow Null](#allow-null)
    - [Item Type](#item-type)
    - [Serializer and Deserializer](#serializer-and-deserializer)
    - [Item Serializer and Item Deserializer](#item-serializer-and-item-deserializer)
- [Exceptions](#exceptions)
    - [SerializationException](#serializationexception)
    - [InvalidInputException](#invalidinputexception)
    - [MissingPropertyException](#missingpropertyexception)
    - [IncorrectTypeException](#incorrecttypeexception)
    - [UnsupportedTypeException](#unsupportedtypeexception)
    - [InvalidEnumBackingException](#invalidenumbackingexception)
- [Custom Serializers](#custom-serializers)

### Installation

[](#installation)

```
composer require aternos/serializer
```

### Usage

[](#usage)

This library adds a simple trait which implements `\JsonSerializable` by serializing all properties with the `#[Serialize]` attribute. This attribute can be used to configure the serialization of the property.

```
use Aternos\Serializer\Serialize;
use Aternos\Serializer\Json\PropertyJsonSerializer;

class ExampleClass implements \JsonSerializable {
    use PropertyJsonSerializer;

    public function __construct(
        #[Serialize]
        protected string $name,
        #[Serialize(required: false)]
        protected int $age = 0,
        #[Serialize(name: "last_name")]
        protected ?string $lastName = null
    ) {

    }
}

$example = new ExampleClass("John", 25, "Doe");

try {
    $json = json_encode($example)
} catch (MissingPropertyException|IncorrectTypeException $e) {
    // handle exception
}
```

See [Exceptions](#exceptions) for more information on error handling.

The trait also adds static `fromJson` and `tryFromJson` methods for deserialization.

```
$example = ExampleClass::fromJson('{ "name": "John", "age": 25, "last_name": "Doe" }');
// ^ throws an exception if the input is invalid (e.g. required property is missing)

$example = ExampleClass::tryFromJson('{ "name": "John", "age": 25, "last_name": "Doe" }');
// ^ returns null if the input is invalid
```

Note

Deserialization is not supported for intersection types as there is no way to determine the correct type.

Note

Serialization and deserialization of enums is only supported for backed enums.

If you prefer you can also serialize and deserialize manually.

```
$example = new ExampleClass("John", 25, "Doe");
$serializer = new \Aternos\Serializer\Json\JsonSerializer();
try {
    $json = $serializer->serialize($example);
} catch (MissingPropertyException|IncorrectTypeException $e) {
    // handle exception
}

$deserializer = new \Aternos\Serializer\Json\JsonDeserializer(ExampleClass::class);
try {
    $example = $deserializer->deserialize($json);
} catch (SerializationException|JsonException $e) {
    // handle exception
}
```

### The Serialize Attribute

[](#the-serialize-attribute)

The `Serialize` attribute can be used to configure the serialization of a property. It has the following options:

#### Name

[](#name)

This option can be used to change the name of the property in the serialized data. If not specified, the property name is used.

This is useful if the serialized data uses a different naming convention (e.g. snake-case).

```
#[Serialize(name: "last_name")]
protected ?string $lastName = null;
```

It also allows serializing properties with identifiers that are not allowed in PHP.

```
#[Serialize(name: "0")]
protected string $zero = "Example";
```

#### Required

[](#required)

This option can be used to specify whether the property is required in the serialized data. If this is not set, the property is not required if it has a default value.

```
#[Serialize]
protected string $name;
// ^ required

#[Serialize]
protected int $age = 1;
// ^ not required
// If not set in the serialized data, the default value (1) is used

#[Serialize(required: true)]
protected string $required = "default";
// ^ required

#[Serialize(required: false)]
protected string $notRequired;
// ^ not required
// If not set in the serialized data, the property is not initialized
// Accessing it before initialization will result in a fatal PHP error
```

#### Allow Null

[](#allow-null)

This option can be used to specify whether the property can be `null` in the serialized data. If this is not set, and the property is annotated with a type the nullability of that type is used. If no type is provided, the property is allowed to be `null`.

```
#[Serialize]
protected string $a;
// ^ does not allow null

#[Serialize(allowNull: false)]
protected ?string $c = null;
// ^ does not allow null

#[Serialize]
protected ?string $b;
// ^ allows null

#[Serialize(allowNull: true)]
protected string $c;
// ^ allows null
// If not set in the serialized data, the property is not initialized
// Accessing it before initialization will result in a fatal PHP error
```

#### Item Type

[](#item-type)

This option can be used to specify the type of the items in an array. It allows the deserializer to convert objects in the array to the correct type. If this is not set, items will not be converted to any type.

Array keys are preserved during the conversion.

```
#[Serialize(itemType: ExampleClass::class)]
protected array $examples;
// ^ items in the array will be converted to ExampleClass

#[Serialize]
protected array $otherExamples;
// ^ items in the array will not be converted
```

#### Serializer and Deserializer

[](#serializer-and-deserializer)

A custom Serializer and Deserializer can be specified for a property. This can be useful if you want to serialize a specific property in a different way.

```
#[Serialize(serializer: new Base64Serializer(), deserializer: new Base64Deserializer(TestClass::class))]
protected TestClass $example;
```

Note that the custom Deserializer is responsible for returning the correct type. If an incompatible type is returned, an IncorrectTypeException is thrown.

#### Item Serializer and Item Deserializer

[](#item-serializer-and-item-deserializer)

Custom Serializers and Deserializers can also be specified for array items.

```
#[Serialize(itemSerializer: new Base64Serializer(), itemDeserializer: new Base64Deserializer(TestClass::class))]
protected array $example = [];
```

### Exceptions

[](#exceptions)

The following exceptions may be thrown during serialization or deserialization:

- [MissingPropertyException](#missingpropertyexception)
- [IncorrectTypeException](#incorrecttypeexception)

Both of these exceptions extend [InvalidInputException](#invalidinputexception).

During deserialization, the following additional exceptions may be thrown:

- [UnsupportedTypeException](#unsupportedtypeexception)
- [InvalidEnumBackingException](#invalidenumbackingexception)
- [JsonException](https://www.php.net/manual/en/class.jsonexception.php)

JsonException is a built-in PHP exception that is thrown when an error occurs during JSON encoding or decoding. All other exceptions extend [SerializationException](#serializationexception) and are described below.

#### SerializationException

[](#serializationexception)

This is a common parent class for all exceptions thrown during serialization or deserialization (except the PHP-built-in JsonException). It is useful for catching, but never instantiated directly.

#### InvalidInputException

[](#invalidinputexception)

This is a parent class for all exceptions caused by an invalid input. During serialization, the input in question is the PHP object you want to serialize. For deserialization, the input refers to the JSON data.

#### MissingPropertyException

[](#missingpropertyexception)

During serialization this is thrown if a required property is not initialized. During deserialization this is thrown if a required property is missing in the input data.

#### IncorrectTypeException

[](#incorrecttypeexception)

During serialization this is thrown if a property has a null value, but does not [allow null](#allow-null). During deserialization this is thrown if a property has a value of an incorrect type (e.g. an int is passed for a string property).

#### UnsupportedTypeException

[](#unsupportedtypeexception)

As noted above, deserializing intersection types is not supported. If an intersection type is encountered during deserialization, this exception is thrown. It's also thrown if a php built-in type is encountered that is not yet supported by the library.

#### InvalidEnumBackingException

[](#invalidenumbackingexception)

This exception is thrown if an enum is deserialized with an invalid backing value. This can happen if the value that is deserialized is not scalar, or if the target enum does not have a matching case.

### Custom Serializers

[](#custom-serializers)

If you want to write a serializer for a different format, you can use the ArraySerializer and ArrayDeserializer class. These convert the object to an associative array and vice versa.

```
$example = new ExampleClass("John", 25, "Doe");
$serializer = new \Aternos\Serializer\Array\ArraySerializer();
$deserializer = new \Aternos\Serializer\Array\ArrayDeserializer(ExampleClass::class);
try {
    $array = $serializer->serialize($example);
    // ^ ['name' => 'John', 'age' => 25, 'last_name' => 'Doe']
    $example = $deserializer->deserialize($array);
} catch (SerializationException $e) {
    // handle exception
}
```

See the JsonSerializer and JsonDeserializer classes for an example implementation.

###  Health Score

41

—

FairBetter than 89% of packages

Maintenance57

Moderate activity, may be stable

Popularity26

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 80.5% 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 ~61 days

Recently: every ~71 days

Total

6

Last Release

284d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/182e603c02f308d1036a1ecaba0b994665e87d13a86ff4550a96c9189a92c544?d=identicon)[aternos](/maintainers/aternos)

---

Top Contributors

[![JulianVennen](https://avatars.githubusercontent.com/u/45244473?v=4)](https://github.com/JulianVennen "JulianVennen (33 commits)")[![KurtThiemann](https://avatars.githubusercontent.com/u/26512466?v=4)](https://github.com/KurtThiemann "KurtThiemann (7 commits)")[![pavog](https://avatars.githubusercontent.com/u/4786628?v=4)](https://github.com/pavog "pavog (1 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[mtdowling/jmespath.php

Declaratively specify how to extract elements from a JSON document

2.0k472.8M135](/packages/mtdowling-jmespathphp)[opis/closure

A library that can be used to serialize closures (anonymous functions) and arbitrary data.

2.6k230.0M284](/packages/opis-closure)[masterminds/html5

An HTML5 parser and serializer.

1.8k242.8M229](/packages/masterminds-html5)[sabberworm/php-css-parser

Parser for CSS Files written in PHP

1.8k191.2M65](/packages/sabberworm-php-css-parser)[michelf/php-markdown

PHP Markdown

3.5k52.4M345](/packages/michelf-php-markdown)[jms/metadata

Class/method/property metadata management in PHP

1.8k152.8M88](/packages/jms-metadata)

PHPackages © 2026

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