Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
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 1 month ago
JSON representation
π§ Laravel + Symfony Serializer. This package provides a bridge between Laravel and Symfony Serializer.
- Host: GitHub
- URL: https://github.com/wayofdev/laravel-symfony-serializer
- Owner: wayofdev
- License: mit
- Created: 2023-06-09T17:00:27.000Z (over 1 year ago)
- Default Branch: master
- Last Pushed: 2024-09-27T15:45:03.000Z (about 2 months ago)
- Last Synced: 2024-09-30T16:04:10.406Z (about 2 months ago)
- Topics: api, data-mapper, data-serialization, data-transformation, json, laravel, laravel-api, laravel-serializer, object-mapping, php8, serialize, serializer, symfony-component, symfony-serializer
- Language: PHP
- Homepage: https://wayof.dev
- Size: 1.18 MB
- Stars: 17
- Watchers: 1
- Forks: 2
- Open Issues: 13
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Contributing: .github/CONTRIBUTING.md
- Funding: .github/FUNDING.yml
- License: LICENSE.md
- Code of conduct: .github/CODE_OF_CONDUCT.md
- Codeowners: .github/CODEOWNERS
- Security: .github/SECURITY.md
Awesome Lists containing this project
README
# 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
## π 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)