Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/wayofdev/laravel-symfony-serializer

πŸ”§ Laravel + Symfony Serializer. This package provides a bridge between Laravel and Symfony Serializer.
https://github.com/wayofdev/laravel-symfony-serializer

api data-mapper data-serialization data-transformation json laravel laravel-api laravel-serializer object-mapping php8 serialize serializer symfony-component symfony-serializer

Last synced: about 13 hours ago
JSON representation

πŸ”§ Laravel + Symfony Serializer. This package provides a bridge between Laravel and Symfony Serializer.

Awesome Lists containing this project

README

        







WayOfDev Logo





Build

Build Status



Project

Total Downloads
Latest Stable Version
Commits since latest release
PHP Version Require



Quality

Codecov
Mutation testing badge
PHP Stan Level 6 of 9



Community

Discord
Follow on Twitter (X)


# Laravel Symfony Serializer

This package integrates the Symfony Serializer component into Laravel, providing a powerful tool for serializing and deserializing objects into various formats such as JSON, XML, CSV, and YAML.

Detailed documentation on the Symfony Serializer can be found on their [official page](https://symfony.com/doc/current/components/serializer.html).


## πŸ—‚οΈ Table of Contents

- [Purpose](#-purpose)
- [Installation](#-installation)
- [Configuration](#-configuration)
- [Configuration Options](#-configuration-options)
- [Custom Strategies](#-custom-strategies)
- [Usage](#-usage)
- [Components](#-components)
- [Example DTO](#-example-dto)
- [Using `SerializerManager` in your Service Classes](#-using-serializermanager-in-service-classes)
- [Using `ResponseFactory` in Laravel Controllers](#-using-responsefactory-in-laravel-controllers)
- [Using in Laravel Queues](#-using-in-laravel-queues)
- [Security Policy](#-security-policy)
- [Want to Contribute?](#-want-to-contribute)
- [Contributors](#-contributors)
- [Social Links](#-social-links)
- [License](#-license)
- [Credits and Useful Resources](#-credits-and-useful-resources)


## πŸ€” Purpose

This package brings the power of the Symfony Serializer component to Laravel. While Laravel does not have a built-in serializer and typically relies on array or JSON transformations, this package provides more advanced serialization capabilities. These include object normalization, handling of circular references, property grouping, and format-specific encoders.

If you are building a REST API, working with queues, or have complex serialization needs, this package will be especially useful. It allows you to use objects as payloads instead of simple arrays and supports various formats such as JSON, XML, CSV, and YAML. This documentation will guide you through the installation process and provide examples of how to use the package to serialize and deserialize your objects.


πŸ™ If you find this repository useful, please consider giving it a ⭐️. Thank you!


## πŸ’Ώ Installation

Require the package as a dependency:

```bash
composer require wayofdev/laravel-symfony-serializer
```

You can publish the config file with:

```bash
$ php artisan vendor:publish \
--provider="WayOfDev\Serializer\Bridge\Laravel\Providers\SerializerServiceProvider" \
--tag="config"
```


## πŸ”§ Configuration

The package configuration file allows you to customize various aspects of the serialization process.

Below is the default configuration provided by the package:

```php
,
* encoderRegistrationStrategy: class-string,
* metadataLoader: class-string|null,
* }
*/
return [
'default' => env('SERIALIZER_DEFAULT_FORMAT', 'symfony-json'),

'debug' => env('SERIALIZER_DEBUG_MODE', env('APP_DEBUG', false)),

'normalizerRegistrationStrategy' => DefaultNormalizerRegistrationStrategy::class,

'encoderRegistrationStrategy' => DefaultEncoderRegistrationStrategy::class,

'metadataLoader' => null,
];
```

### β†’ Configuration Options

- **`default`**: Specifies the default serializer format. This can be overridden by setting the `SERIALIZER_DEFAULT_FORMAT` environment variable. The default is `symfony-json`.
- **`debug`**: Enables debug mode for `ProblemNormalizer`. This can be set using the `SERIALIZER_DEBUG_MODE` environment variable. It defaults to the `APP_DEBUG` value.
- **`normalizerRegistrationStrategy`**: Specifies the strategy class for registering normalizers. The default strategy is [`WayOfDev\Serializer\DefaultNormalizerRegistrationStrategy`](https://github.com/wayofdev/laravel-symfony-serializer/blob/master/src/DefaultNormalizerRegistrationStrategy.php).
- **`encoderRegistrationStrategy`**: Specifies the strategy class for registering encoders. The default strategy is [`WayOfDev\Serializer\DefaultEncoderRegistrationStrategy`](https://github.com/wayofdev/laravel-symfony-serializer/blob/master/src/DefaultEncoderRegistrationStrategy.php).
- **`metadataLoader`**: Allows registration of a custom metadata loader. By default, `Symfony\Component\Serializer\Mapping\Loader\AttributeLoader` is used.

### β†’ Custom Strategies

[Due to Laravel's caching limitations, where configs cannot instantiate objects](https://elliotderhay.com/blog/caching-laravel-configs-that-use-objects), this package uses strategies to register normalizers and encoders.

You can create custom normalizer or encoder registration strategies by implementing the respective interfaces.

#### Normalizer Registration Strategy

To create a custom normalizer registration strategy:

1. Implement the [`NormalizerRegistrationStrategy`](https://github.com/wayofdev/laravel-symfony-serializer/blob/master/src/Contracts/NormalizerRegistrationStrategy.php) interface:

```php
}>
*/
public function normalizers(): iterable
{
// ...
}
}
```

2. Change `serializer.php` config to use your custom strategy:

```php
'normalizerRegistrationStrategy' => CustomNormalizerRegistrationStrategy::class,
```

#### Encoder Registration Strategy

To create a custom encoder registration strategy:

1. Implement the [`EncoderRegistrationStrategy`](https://github.com/wayofdev/laravel-symfony-serializer/blob/master/src/Contracts/EncoderRegistrationStrategy.php) interface:

```php

*/
public function encoders(): iterable
{
// Register your encoders here...

yield ['encoder' => new Encoder\JsonEncoder()];
yield ['encoder' => new Encoder\CsvEncoder()];
yield ['encoder' => new Encoder\XmlEncoder()];

if (class_exists(Dumper::class)) {
yield ['encoder' => new Encoder\YamlEncoder()];
}
}
}
```

2. Change `serializer.php` config to use your custom strategy:

```php
'encoderRegistrationStrategy' => CustomEncoderRegistrationStrategy::class,
```


## πŸ’» Usage

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

The default 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.

### β†’ Components

#### SerializerManager

The `SerializerManager` handles the different serializers available in this package. It can be used to serialize and deserialize objects.

#### ResponseFactory

The `ResponseFactory` is used to create responses in Laravel controllers, making it easy to include serialized data in HTTP responses.

#### Facades

This package includes two Laravel Facades:

- `Manager` β€” To access the underlying `SerializerManager`
- `Serializer` β€” To access the bound and configured original Symfony Serializer instance.

### β†’ Example DTO

We will use this example DTO for serialization purposes:

```php
id = $id;
$this->name = $name;
$this->email = $email;
}

public function id(): int
{
return $this->id;
}

public function name(): string
{
return $this->name;
}

public function email(): string
{
return $this->email;
}
}
```

### β†’ Using `SerializerManager` in Service Classes

```php
serializer->serializer('symfony-json');
$dto = new UserDTO(1, 'John Doe', '[email protected]');

$serialized = $serializer->serialize(
payload: $dto,
context: ['groups' => ['private']]
);
}
}
```

### β†’ Using `ResponseFactory` in Laravel Controllers

Here's an example of how you can use the `ResponseFactory` in a Laravel Controller:

**Example Controller:**

```php
response->withContext(['groups' => ['private']]);
$this->response->withStatusCode(HttpCode::HTTP_OK);

return $this->response->create($dto);
}
}
```


### β†’ Using in Laravel Queues

To switch from Laravel's default serialization to this implementation in queues, you can override the `__serialize` and `__unserialize` methods in your queue jobs. Here’s an example:

```php
product = $product;
}

public function handle(ProductProcessor $processor): void
{
$processor->process($this->product);
}

public function __serialize(): array
{
return [
'product' => Manager::serialize($this->product),
];
}

public function __unserialize(array $values): void
{
$this->product = Manager::deserialize($values['product'], Product::class);
}
}
```


## πŸ”’ Security Policy

This project has a [security policy](.github/SECURITY.md).


## πŸ™Œ Want to Contribute?

Thank you for considering contributing to the wayofdev community! We welcome all kinds of contributions. If you want to:

- πŸ€” [Suggest a feature](https://github.com/wayofdev/laravel-symfony-serializer/issues/new?assignees=&labels=type%3A+enhancement&projects=&template=2-feature-request.yml&title=%5BFeature%5D%3A+)
- πŸ› [Report an issue](https://github.com/wayofdev/laravel-symfony-serializer/issues/new?assignees=&labels=type%3A+documentation%2Ctype%3A+maintenance&projects=&template=1-bug-report.yml&title=%5BBug%5D%3A+)
- πŸ“– [Improve documentation](https://github.com/wayofdev/laravel-symfony-serializer/issues/new?assignees=&labels=type%3A+documentation%2Ctype%3A+maintenance&projects=&template=4-docs-bug-report.yml&title=%5BDocs%5D%3A+)
- πŸ‘¨β€πŸ’» [Contribute to the code](.github/CONTRIBUTING.md)

You are more than welcome. Before contributing, please check our [contribution guidelines](.github/CONTRIBUTING.md).

[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg?style=for-the-badge)](https://conventionalcommits.org)


## 🫑 Contributors



Contributors Badge





## 🌐 Social Links

- **Twitter:** Follow our organization [@wayofdev](https://twitter.com/intent/follow?screen_name=wayofdev) and the author [@wlotyp](https://twitter.com/intent/follow?screen_name=wlotyp).
- **Discord:** Join our community on [Discord](https://discord.gg/CE3TcCC5vr).


## πŸ“œ License

[![License](https://img.shields.io/github/license/wayofdev/laravel-symfony-serializer?style=for-the-badge&color=blue)](./LICENSE.md)


## 🧱 Credits and Useful Resources

This repository is inspired by the following projects:

- [spiral/serializer](https://github.com/spiral/serializer)
- [spiral-packages/symfony-serializer](https://github.com/spiral-packages/symfony-serializer)
- [jeromegamez/ramsey-uuid-normalizer](https://github.com/jeromegamez/ramsey-uuid-normalizer)
- [wayofdev/laravel-jms-serializer](https://github.com/wayofdev/laravel-jms-serializer)
- [symfony/serializer](https://github.com/symfony/serializer)