PHPackages                             spiral-packages/symfony-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. spiral-packages/symfony-serializer

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

spiral-packages/symfony-serializer
==================================

Symfony serializer bridge for Spiral Framework

2.2.0(2y ago)21.4M↓35.4%12MITPHPPHP ^8.1CI passing

Since Sep 13Pushed 1y ago2 watchersCompare

[ Source](https://github.com/spiral-packages/symfony-serializer)[ Packagist](https://packagist.org/packages/spiral-packages/symfony-serializer)[ Docs](https://github.com/spiral-packages/symfony-serializer)[ RSS](/packages/spiral-packages-symfony-serializer/feed)WikiDiscussions 2.x Synced 1mo ago

READMEChangelog (6)Dependencies (14)Versions (8)Used By (2)

Symfony serializer bridge for Spiral Framework
==============================================

[](#symfony-serializer-bridge-for-spiral-framework)

[![PHP Version Require](https://camo.githubusercontent.com/f9630862db09ee894c46851cb820238850ce1ce22235967b309ab3c985e17b03/68747470733a2f2f706f7365722e707567782e6f72672f73706972616c2d7061636b616765732f73796d666f6e792d73657269616c697a65722f726571756972652f706870)](https://packagist.org/packages/spiral-packages/symfony-serializer)[![Latest Stable Version](https://camo.githubusercontent.com/36a87a2a7bea94a4623ce2542b0e803f9a24491c7677565148c1393ae9f7a323/68747470733a2f2f706f7365722e707567782e6f72672f73706972616c2d7061636b616765732f73796d666f6e792d73657269616c697a65722f762f737461626c65)](https://packagist.org/packages/spiral-packages/symfony-serializer)[![phpunit](https://github.com/spiral-packages/symfony-serializer/actions/workflows/phpunit.yml/badge.svg)](https://github.com/spiral-packages/symfony-serializer/actions)[![psalm](https://github.com/spiral-packages/symfony-serializer/actions/workflows/psalm.yml/badge.svg)](https://github.com/spiral-packages/symfony-serializer/actions)[![Total Downloads](https://camo.githubusercontent.com/d5a506f0247ab4803305a9bb0bc06cf25785deb58f78855c1f12c166a78a1c13/68747470733a2f2f706f7365722e707567782e6f72672f73706972616c2d7061636b616765732f73796d666f6e792d73657269616c697a65722f646f776e6c6f616473)](https://packagist.org/packages/spiral-packages/symfony-serializer)

This package provides an extension to the default list of serializers in Spiral Framework, allowing you to easily serialize and deserialize objects into various formats such as `JSON`, `XML`, `CSV`, and `YAML`.

> **Note**Read more about spiral/serializer component in the official [documentation](https://spiral.dev/docs/advanced-serializer).

If you are building a REST API or working with queues, this package will be especially useful as it allows you to use objects as payload instead of simple arrays.

This documentation will guide you through the installation process and provide examples of how to use the package to serialize and deserialize your objects.

Requirements
------------

[](#requirements)

Make sure that your server is configured with following PHP version and extensions:

- PHP 8.1+
- Spiral framework ^3.7
- Symfony Serializer Component ^6.4 || ^7.0
- Symfony PropertyAccess Component ^6.4 || ^7.0

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

[](#installation)

You can install the package via composer:

```
composer require spiral-packages/symfony-serializer
```

After package install you need to register bootloader from the package.

```
protected const LOAD = [
    // ...
    \Spiral\Serializer\Symfony\Bootloader\SerializerBootloader::class,
];
```

> **Note**Bootloader `Spiral\Serializer\Bootloader\SerializerBootloader` can be removed. If you are using [`spiral-packages/discoverer`](https://github.com/spiral-packages/discoverer), you don't need to register bootloader by yourself.

Configuration
-------------

[](#configuration)

The package comes with default configurations for `normalizers`, `encoders`, and `metadataLoader`. However, you can change these configurations based on your project's requirements.

**There are two ways to configure the package:**

### Config file

[](#config-file)

You can create a configuration file `app/config/symfony-serializer.php` and define `normalizers`, `encoders`, and `Symfony\Component\Serializer\Mapping\Loader\LoaderInterface`for `Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory` used by the Symfony Serializer component parameters to extend the default configuration.

**Here is an example of the configuration file:**

```
use Symfony\Component\Serializer\Encoder;
use Symfony\Component\Serializer\Normalizer;
use Symfony\Component\Serializer\Mapping\Loader\AttributeLoader;
use Spiral\Core\Container\Autowire;

return [
    'normalizers' => [
        new Normalizer\UnwrappingDenormalizer(),
        new Normalizer\ProblemNormalizer(debug: false),
        new Normalizer\UidNormalizer(),
        new Normalizer\JsonSerializableNormalizer(),
        new Normalizer\DateTimeNormalizer(),
        new Normalizer\ConstraintViolationListNormalizer(),
        new Normalizer\MimeMessageNormalizer(new Normalizer\PropertyNormalizer()),
        new Normalizer\DateTimeZoneNormalizer(),
        new Normalizer\DateIntervalNormalizer(),
        new Normalizer\FormErrorNormalizer(),
        new Normalizer\BackedEnumNormalizer(),
        new Normalizer\DataUriNormalizer(),
        new Autowire(Normalizer\ArrayDenormalizer::class), // by Autowire
        Normalizer\ObjectNormalizer::class, // by class string
    ],
    'encoders' => [
        new Encoder\JsonEncoder(),
        new Encoder\CsvEncoder(),
        Encoder\XmlEncoder::class,
        new Autowire(Encoder\YamlEncoder::class),
    ],
    'metadataLoader' => new AttributeLoader() // by default
 //  Other available loaders:
 // 'metadataLoader' => new YamlFileLoader('/path/to/your/definition.yaml')
 // 'metadataLoader' => new XmlFileLoader('/path/to/your/definition.xml')
];
```

### Bootloader

[](#bootloader)

`Spiral\Serializer\Symfony\EncodersRegistryInterface` and `Spiral\Serializer\Symfony\NormalizersRegistryInterface`provided by the package to add your own normalizers or encoders. You can register your own `normalizers` or `encoders`using the `register` method provided by these interfaces.

**Here is an example:**

```
namespace App\Application\Bootloader;

use Spiral\Serializer\Symfony\EncodersRegistryInterface;
use Spiral\Serializer\Symfony\NormalizersRegistryInterface;
use Spiral\Boot\Bootloader\Bootloader;

final class AppBootloader extends Bootloader
{
    public function boot(
        NormalizersRegistryInterface $normalizersRegistry,
        EncodersRegistryInterface $encodersRegistry,
    ): void {
        // Add CustomNormalizer before ObjectNormalizer
        $normalizersRegistry->register(normalizer: new CustomNormalizer(), priority: 699);

        $encodersRegistry->register(new CustomEncoder());
    }
}
```

Usage
-----

[](#usage)

The package provides a list of serializers that can be used to serialize and deserialize objects.

The serializers available in this package are: `symfony-json`, `symfony-csv`, `symfony-xml`, `symfony-yaml`.

> **Warning**The `yaml` encoder requires the `symfony/yaml` package and is disabled when the package is not installed. Install the `symfony/yaml` package and the encoder will be automatically enabled.

**Here are several ways to use these serializers:**

### 1. Set a default serializer

[](#1-set-a-default-serializer)

You can set a desired Symfony serializer as the default application serializer by setting the `DEFAULT_SERIALIZER_FORMAT` environment variable.

```
DEFAULT_SERIALIZER_FORMAT=symfony-json
```

Once the default serializer is set, you can request the `Spiral\Serializer\SerializerInterface` from the container and use it to serialize and deserialize objects.

**Serialization:**

```
use Spiral\Serializer\SerializerInterface;
use App\Repository\PostRepository;

final class PostController
{
    public function __construct(
        private readonly SerializerInterface $serializer,
        private readonly PostRepository $repository,
    ) {}

    public function show(string $postId): string
    {
        $post = $this->repository->find($postId);

        return $this->serializer->serialize($post);
    }
}
```

**Deserialization:**

```
use App\Entity\Post;use Spiral\Serializer\SerializerInterface;

final class PostService
{
    public function __construct(
        private readonly SerializerInterface $serializer,
        private readonly HttpClient $http,
    ) {}

    public function show(string $postId): Post
    {
        $json = $this->http->get('https://example.com/posts/' . $postId);

        return $this->serializer->unserialize($json, Post::class);
    }
}
```

### 2. Using with the Serializer Manager

[](#2-using-with-the-serializer-manager)

You can request a desired serializer from `Spiral\Serializer\SerializerManager` by its name. Once you have the serializer, you can use it to serialize and deserialize objects.

**Serialization:**

```
use Spiral\Serializer\SerializerManager;
use Spiral\Serializer\SerializerInterface;
use App\Repository\PostRepository;

final class PostController
{
    private readonly SerializerInterface $serializer;

    public function __construct(
        SerializerManager $manager,
        private readonly PostRepository $repository,
    ) {
        $this->serializer = $manager->getSerializer('symfony-json');
    }

    public function show(string $postId): string
    {
        $post = $this->repository->find($postId);

        return $this->serializer->serialize($post);
    }
}
```

**Deserialization:**

```
use App\Entity\Post;use Spiral\Serializer\SerializerInterface;

final class PostService
{
    private readonly SerializerInterface $serializer;

    public function __construct(
        SerializerManager $manager,
        private readonly HttpClient $http,
    ) {
        $this->serializer = $manager->getSerializer('symfony-json');
    }

    public function show(string $postId): Post
    {
        $json = $this->http->get('https://example.com/posts/' . $postId);

        return $this->serializer->unserialize($json, Post::class);
    }
}
```

Alternatively, you can use the `serialize` and `unserialize` methods of the manager class:

```
use Psr\Container\ContainerInterface;
use Spiral\Serializer\SerializerManager;
use App\Repository\PostRepository;
use App\Entity\Post;

/** @var PostRepository $repository */
$post = $repository->find($postId);
/** @var ContainerInterface $container */
$manager = $container->get(SerializerManager::class);

$serializedString = $manager->serialize($post , 'symfony-json');

$post = $manager->unserialize($serializedString , Post::class, 'symfony-json');
```

### 3. Using with Symfony Serializer

[](#3-using-with-symfony-serializer)

You can also use the Symfony Serializer directly by requesting the `Symfony\Component\Serializer\SerializerInterface`from the container. Once you have the serializer, you can use it to `serialize` and `deserialize` objects.

**Here's an example:**

```
use Symfony\Component\Serializer\SerializerInterface;

$serializer = $this->container->get(SerializerInterface::class);

$result = $serializer->serialize($payload, 'symfony-json', $context);
$result = $serializer->deserialize($payload, Post::class, 'symfony-json', $context);
```

### Additional methods

[](#additional-methods)

Symfony Serializer Manager provides additional methods to work with data:

- **normalize**: This method takes in `data` and a `format` and returns a value that represents the normalized data. The context parameter can also be passed to control the normalization process.
- **denormalize**: This method takes in `data`, a `type`, a `format`, and a `context`, and returns an object that represents the denormalized data.
- **supportsNormalization**: This method takes in `data`, a `format`, and a `context`, and returns a `boolean`indicating whether the given data can be normalized by the serializer.
- **supportsDenormalization**: This method takes in `data`, a `type`, a `format`, and a `context`, and returns a `boolean` indicating whether the given data can be denormalized by the serializer.
- **encode**: This method takes in `data`, a `format`, and a `context`, and returns a `string` that represents the encoded data.
- **decode**: This method takes in `data`, a `format`, and a `context`, and returns a `value` that represents the decoded data.
- **supportsEncoding**: This method takes in a `format` and a `context`, and returns a `boolean` indicating whether the given format can be used to encode data by the serializer.
- **supportsDecoding**: This method takes in a `format` and a `context`, and returns a `boolean` indicating whether the given format can be used to decode data by the serializer.

```
use Spiral\Serializer\SerializerManager;

$manager = $this->container->get(SerializerManager::class);

// Getting a serializer `Spiral\Serializer\Symfony\Serializer`
$serializer = $manager->getSerializer('symfony-json');

$serializer->normalize($data, $format, $context);
$serializer->denormalize($data, $type, $format, $context);

$serializer->supportsNormalization($data, $format, $context);
$serializer->supportsDenormalization($data, $type, $format, $context);

$serializer->encode($data, $format, $context);
$serializer->decode($data, $format, $context);

$serializer->supportsEncoding($format, $context);
$serializer->supportsDecoding($format, $context);
```

These methods provide additional flexibility for working with different data formats and can be useful in certain scenarios.

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE) for more information.

###  Health Score

41

—

FairBetter than 89% of packages

Maintenance29

Infrequent updates — may be unmaintained

Popularity44

Moderate usage in the ecosystem

Community18

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

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

Recently: every ~139 days

Total

8

Last Release

567d ago

Major Versions

1.x-dev → 2.0.02023-04-20

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/773481?v=4)[Pavel Buchnev](/maintainers/butschster)[@butschster](https://github.com/butschster)

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

---

Top Contributors

[![msmakouz](https://avatars.githubusercontent.com/u/67324318?v=4)](https://github.com/msmakouz "msmakouz (30 commits)")[![butschster](https://avatars.githubusercontent.com/u/773481?v=4)](https://github.com/butschster "butschster (24 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (7 commits)")[![roxblnfk](https://avatars.githubusercontent.com/u/4152481?v=4)](https://github.com/roxblnfk "roxblnfk (2 commits)")

---

Tags

composerhacktoberfestpackagephp81spiral-frameworksymfony-componentserializerspiralspiral-packagessymfony-serializer

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm

Type Coverage Yes

### Embed Badge

![Health badge](/badges/spiral-packages-symfony-serializer/health.svg)

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

###  Alternatives

[symfony/serializer-pack

A pack for the Symfony serializer

1.1k28.2M221](/packages/symfony-serializer-pack)[api-platform/serializer

API Platform core Serializer

223.4M31](/packages/api-platform-serializer)[api-platform/symfony

Symfony API Platform integration

323.2M67](/packages/api-platform-symfony)[flix-tech/avro-serde-php

A library to serialize and deserialize Avro records making use of the confluent schema registry

674.0M17](/packages/flix-tech-avro-serde-php)[chameleon-system/chameleon-base

The Chameleon System core.

1026.5k3](/packages/chameleon-system-chameleon-base)[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)
