PHPackages                             astral/php-serialize - 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. [API Development](/categories/api)
4. /
5. astral/php-serialize

ActiveLibrary[API Development](/categories/api)

astral/php-serialize
====================

An advanced PHP serialization tool leveraging attributes for flexible object-to-array and JSON conversion. Supports property aliases, type conversions, and nested object handling. Ideal for APIs, data persistence, and configuration management.

v1.1.4(7mo ago)1241MITPHPPHP ^8.1CI passing

Since Jan 24Pushed 7mo ago1 watchersCompare

[ Source](https://github.com/astral-data/php-serialize)[ Packagist](https://packagist.org/packages/astral/php-serialize)[ Docs](https://github.com/astral-data/php-serialize)[ RSS](/packages/astral-php-serialize/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (10)Versions (13)Used By (0)

[![Total Downloads](https://camo.githubusercontent.com/310f335ec1c1a9ec0d29c577f73641afb18580250088287d2482de4393216988/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f61737472616c2f7068702d73657269616c697a652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/astral/php-serialize)[![Tests](https://github.com/astral-data/php-serialize/actions/workflows/test.yml/badge.svg)](https://github.com/astral-data/php-serialize/actions/workflows/test.yml)[![PHPStan](https://github.com/astral-data/php-serialize/actions/workflows/phpstan.yml/badge.svg)](https://github.com/astral-data/php-serialize/actions/workflows/phpstan.yml)

Languages
=========

[](#languages)

- [Complete documen-English](https://astrals-organization.gitbook.io/php-serialize/php-serialize-en)
- [完整文档-中文](https://astrals-organization.gitbook.io/php-serialize)

php-serialize
=============

[](#php-serialize)

**php-serialize** is a powerful attribute-based serialization library for PHP (requires **PHP ≥ 8.1**).
It allows you to map objects to arrays/JSON and **automatically generate OpenAPI documentation** based on the same attributes.

> 🚀 Unified solution for API data serialization and documentation generation.

✨ Features
----------

[](#-features)

- 🏷️ Property aliasing with
- 🔄 Automatic type casting (e.g. `DateTime ↔ string`)
- 🔁 Deep object nesting support
- ❌ Skip/exclude fields with
- 🧩 Recursive DTO serialization
- 🧬 **Auto-generate OpenAPI schema** using object definitions
- ⚙️ Framework-agnostic — works with Laravel, Symfony, etc.

Benchmark
---------

[](#benchmark)

```
    Run vendor/bin/phpbench run benchmarks/ --bootstrap=vendor/autoload.php
    PHPBench (1.4.1) running benchmarks... #standwithukraine
    with PHP version 8.4.8, xdebug ❌, opcache ❌

    benchObjectCreation.....................I4 ✔ Mo117.841μs (±3.09%)
    benchObjectCreationWithoutCache.........I4 ✔ Mo284.568μs (±0.71%)
    benchObjectToArray......................I4 ✔ Mo62.883μs (±0.56%)
    benchObjectToArrayWithoutCache..........I4 ✔ Mo211.700μs (±0.84%)
```

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

[](#quick-start)

### Installation

[](#installation)

Install using Composer:

```
composer require astral/php-serialize
```

### Basic Usage

[](#basic-usage)

```
use Astral\Serialize\Serialize;

class User extends Serialize {
    public string $name,
    public int $age
}

// Create object from array
$user = User::from([
    'name' => 'John Doe',
    'age' => 30
]);

// Access object properties
echo $user->name;  // Output: John Doe
echo $user->age;   // Output: 30

// Convert to array
$userArray = $user->toArray();
// $userArray contents:
// [
//     'name' => 'John Doe',
//     'age' => 30
// ]
```

#### Other Features

[](#other-features)

1. **Immutability**: Read-only properties cannot be modified after construction

```
use Astral\Serialize\Serialize;

class User extends Serialize {
    public function __construct(
        public readonly string $name,
        public readonly int $age
    ) {}
}

$user = User::from([
    'name' => 'John Doe',
    'age' => 30
]);

try {
    $user->name = 'Jane Doe';  // Compile-time error: cannot modify read-only property
} catch (Error $e) {
    echo "Read-only properties cannot be reassigned";
}
```

2. **Type-Safe Initialization**

```
$user = User::from([
    'name' => 123,       // Integer will be converted to string
    'age' => '35'        // String will be converted to integer
]);

echo $user->name;  // Output: "123"
echo $user->age;   // Output: 35
```

3. **Constructor Initialization**

```
use Astral\Serialize\Serialize;

class User extends Serialize {
    public function __construct(
        public readonly string $name,
        public readonly int $age
    ) {
        // Can add additional validation or processing logic in the constructor
        if (strlen($name) < 2) {
            throw new \InvalidArgumentException('Name is too short');
        }
    }
}
```

Auto Create OpenApi Doc
-----------------------

[](#auto-create-openapi-doc)

### Creating Request

[](#creating-request)

```
use Astral\Serialize\Serialize;

class UserAddRequest extends Serialize {
    public string $name;
    public int $id;
}

class UserDetailRequest extends Serialize {
    public int $id;
}
```

### Creating Response

[](#creating-response)

```
use Astral\Serialize\Serialize;

class UserDto extends Serialize {
    public string $name,
    public int $id;
}
```

### Creating Controller

[](#creating-controller)

```
use Astral\Serialize\Serialize;
use Astral\Serialize\OpenApi\Enum\MethodEnum;

#[\Astral\Serialize\OpenApi\Annotations\Tag('User Module Management')]
class UserController {

    #[\Astral\Serialize\OpenApi\Annotations\Summary('Create User')]
    #[\Astral\Serialize\OpenApi\Annotations\Route('/user/create')]
    #[\Astral\Serialize\OpenApi\Annotations\RequestBody(UserAddRequest::class)]
     #[\Astral\Serialize\OpenApi\Annotations\Response(UserDto::class)]
    public function create()
    {
        return new UserDto();
    }

    #[\Astral\Serialize\OpenApi\Annotations\Summary('User Detail')]
    #[\Astral\Serialize\OpenApi\Annotations\Route(route:'/user/detail', method: MethodEnum::GET)]
    public function detail(UserDetailRequest $request): UserDto
    {
        return new UserDto();
    }
}
```

### Starting the Service

[](#starting-the-service)

#### Docker Deployment

[](#docker-deployment)

Navigate to the project root directory first:

```
docker run  -v $PWD/vendor/astral/php-serialize/src/OpenApi/Frankenphp/Caddyfile:/etc/frankenphp/Caddyfile -v $PWD:/app -p 8089:80 dunglas/frankenphp
```

Access `http://127.0.0.1:8089/docs` to view the documentation.

[![UI-IMG](./docs/en/openapi/ui.png)](./docs/en/openapi/ui.png)

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance64

Regular maintenance activity

Popularity15

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity54

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

Total

10

Last Release

220d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/271551dfd20a95b89debef07d372c6d15b07a9edc1df86ee9d9f2246fc1c643d?d=identicon)[astral-data](/maintainers/astral-data)

---

Top Contributors

[![astral-data](https://avatars.githubusercontent.com/u/14285946?v=4)](https://github.com/astral-data "astral-data (116 commits)")

---

Tags

api-developmentdtoobject-to-arrayopenapi3php-serializephp8serializationswaggerserializephp-serializephp-mapper

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/astral-php-serialize/health.svg)

```
[![Health](https://phpackages.com/badges/astral-php-serialize/health.svg)](https://phpackages.com/packages/astral-php-serialize)
```

###  Alternatives

[thecodingmachine/graphqlite

Write your GraphQL queries in simple to write controllers (using webonyx/graphql-php).

5723.1M30](/packages/thecodingmachine-graphqlite)[esign/laravel-conversions-api

A laravel wrapper package around the Facebook Conversions API

69145.4k](/packages/esign-laravel-conversions-api)[nilportugues/serializer

Serialize PHP variables, including objects, in any format. Support to unserialize it too.

51259.4k6](/packages/nilportugues-serializer)[tochka-developers/jsonrpc

JsonRpc extension for Laravel

2733.8k1](/packages/tochka-developers-jsonrpc)[wayofdev/laravel-symfony-serializer

📦 Laravel wrapper around Symfony Serializer.

2113.6k](/packages/wayofdev-laravel-symfony-serializer)

PHPackages © 2026

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