Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork3
🔧 Laravel + Symfony Serializer. This package provides a bridge between Laravel and Symfony Serializer.
License
wayofdev/laravel-symfony-serializer
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
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 theirofficial page.
- Purpose
- Installation
- Configuration
- Usage
- Security Policy
- Want to Contribute?
- Contributors
- Social Links
- License
- Credits and Useful Resources
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!
Require the package as a dependency:
composer require wayofdev/laravel-symfony-serializer
You can publish the config file with:
$ php artisan vendor:publish \ --provider="WayOfDev\Serializer\Bridge\Laravel\Providers\SerializerServiceProvider" \ --tag="config"
The package configuration file allows you to customize various aspects of the serialization process.
Below is the default configuration provided by the package:
<?phpdeclare(strict_types=1);useSymfony\Component\Serializer\Mapping\Loader\LoaderInterface;useWayOfDev\Serializer\Contracts\EncoderRegistrationStrategy;useWayOfDev\Serializer\Contracts\NormalizerRegistrationStrategy;useWayOfDev\Serializer\DefaultEncoderRegistrationStrategy;useWayOfDev\Serializer\DefaultNormalizerRegistrationStrategy;/** * @return array{ * default: string, * debug: bool, * normalizerRegistrationStrategy: class-string<NormalizerRegistrationStrategy>, * encoderRegistrationStrategy: class-string<EncoderRegistrationStrategy>, * metadataLoader: class-string<LoaderInterface>|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,];
default: Specifies the default serializer format. This can be overridden by setting theSERIALIZER_DEFAULT_FORMATenvironment variable. The default issymfony-json.debug: Enables debug mode forProblemNormalizer. This can be set using theSERIALIZER_DEBUG_MODEenvironment variable. It defaults to theAPP_DEBUGvalue.normalizerRegistrationStrategy: Specifies the strategy class for registering normalizers. The default strategy isWayOfDev\Serializer\DefaultNormalizerRegistrationStrategy.encoderRegistrationStrategy: Specifies the strategy class for registering encoders. The default strategy isWayOfDev\Serializer\DefaultEncoderRegistrationStrategy.metadataLoader: Allows registration of a custom metadata loader. By default,Symfony\Component\Serializer\Mapping\Loader\AttributeLoaderis used.
Due to Laravel's caching limitations, where configs cannot instantiate objects, this package uses strategies to register normalizers and encoders.
You can create custom normalizer or encoder registration strategies by implementing the respective interfaces.
To create a custom normalizer registration strategy:
Implement the
NormalizerRegistrationStrategyinterface:<?phpdeclare(strict_types=1);namespaceInfrastructure\Serializer;useSymfony\Component\Serializer\Mapping\Loader\LoaderInterface;useSymfony\Component\Serializer\Normalizer;useSymfony\Component\Serializer\Normalizer\DenormalizerInterface;useSymfony\Component\Serializer\Normalizer\NormalizerInterface;useWayOfDev\Serializer\Contracts\NormalizerRegistrationStrategy;// ...finalreadonlyclass CustomNormalizerRegistrationStrategyimplements NormalizerRegistrationStrategy{publicfunction__construct(privateLoaderInterface$loader,privatebool$debugMode =false, ) { }/** * @return iterable<array{normalizer: NormalizerInterface|DenormalizerInterface, priority: int<0, max>}> */publicfunctionnormalizers():iterable {// ... }}
Change
serializer.phpconfig to use your custom strategy:'normalizerRegistrationStrategy' => CustomNormalizerRegistrationStrategy::class,
To create a custom encoder registration strategy:
Implement the
EncoderRegistrationStrategyinterface:<?phpdeclare(strict_types=1);namespaceInfrastructure\Serializer;useSymfony\Component\Serializer\Encoder;useSymfony\Component\Serializer\Encoder\DecoderInterface;useSymfony\Component\Serializer\Encoder\EncoderInterface;useSymfony\Component\Yaml\Dumper;usefunctionclass_exists;finalclass CustomEncoderRegistrationStrategyimplementsContracts\EncoderRegistrationStrategy{/** * @return iterable<array{encoder: EncoderInterface|DecoderInterface}> */publicfunctionencoders():iterable {// Register your encoders here...yield ['encoder' =>newEncoder\JsonEncoder()];yield ['encoder' =>newEncoder\CsvEncoder()];yield ['encoder' =>newEncoder\XmlEncoder()];if (class_exists(Dumper::class)) {yield ['encoder' =>newEncoder\YamlEncoder()]; } }}
Change
serializer.phpconfig to use your custom strategy:'encoderRegistrationStrategy' => CustomEncoderRegistrationStrategy::class,
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
Theyaml encoder requires thesymfony/yaml package and is disabled when the package is not installed.Install thesymfony/yaml package, and the encoder will be automatically enabled.
TheSerializerManager handles the different serializers available in this package. It can be used to serialize and deserialize objects.
TheResponseFactory is used to create responses in Laravel controllers, making it easy to include serialized data in HTTP responses.
This package includes two Laravel Facades:
Manager— To access the underlyingSerializerManagerSerializer— To access the bound and configured original Symfony Serializer instance.
We will use this example DTO for serialization purposes:
<?phpnamespaceApplication\User;useSymfony\Component\Serializer\Annotation\Groups;useSymfony\Component\Serializer\Annotation\SerializedName;class UserDTO{ #[Groups(['public'])] #[SerializedName('id')]privateint$id; #[Groups(['public'])] #[SerializedName('name')]privatestring$name; #[Groups(['private','public'])] #[SerializedName('emailAddress')]privatestring$email;publicfunction__construct(int$id,string$name,string$email) {$this->id =$id;$this->name =$name;$this->email =$email; }publicfunctionid():int {return$this->id; }publicfunctionname():string {return$this->name; }publicfunctionemail():string {return$this->email; }}
<?phpnamespaceApplication\Services;useWayOfDev\Serializer\Manager\SerializerManager;useApplication\User\UserDTO;class ProductService{publicfunction__construct(privatereadonlySerializerManager$serializer, ) { }publicfunctionsomeMethod():void {$serializer =$this->serializer->serializer('symfony-json');$dto =newUserDTO(1,'John Doe','john@example.com');$serialized =$serializer->serialize( payload:$dto, context: ['groups' => ['private']] ); }}
Here's an example of how you can use theResponseFactory in a Laravel Controller:
Example Controller:
<?phpnamespaceBridge\Laravel\Public\Product\Controllers;useApplication\User\UserDTO;useIlluminate\Http\Request;useWayOfDev\Serializer\Bridge\Laravel\Http\HttpCode;useWayOfDev\Serializer\Bridge\Laravel\Http\ResponseFactory;class UserControllerextends Controller{publicfunction__construct(privateResponseFactory$response) { }publicfunctionindex() {$dto =newUserDTO(1,'John Doe','john@example.com');$this->response->withContext(['groups' => ['private']]);$this->response->withStatusCode(HttpCode::HTTP_OK);return$this->response->create($dto); }}
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:
<?phpdeclare(strict_types=1);namespaceBridge\Laravel\Public\Product\Jobs;useDomain\Product\Models\Product;useDomain\Product\ProductProcessor;useIlluminate\Bus\Queueable;useIlluminate\Contracts\Queue\ShouldQueue;useIlluminate\Foundation\Bus\Dispatchable;useIlluminate\Queue\InteractsWithQueue;useIlluminate\Queue\SerializesModels;useWayOfDev\Serializer\Bridge\Laravel\Facades\Manager;/** * This Job class shows how Symfony Serializer can be used with Laravel Queues. */class ProcessProductJobimplements ShouldQueue{use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;publicProduct$product;publicfunction__construct(Product$product) {$this->product =$product; }publicfunctionhandle(ProductProcessor$processor):void {$processor->process($this->product); }publicfunction__serialize():array {return ['product' => Manager::serialize($this->product), ]; }publicfunction__unserialize(array$values):void {$this->product = Manager::deserialize($values['product'], Product::class); }}
This project has asecurity policy.
Thank you for considering contributing to the wayofdev community! We welcome all kinds of contributions. If you want to:
You are more than welcome. Before contributing, please check ourcontribution guidelines.
- Twitter: Follow our organization@wayofdev and the author@wlotyp.
- Discord: Join our community onDiscord.
This repository is inspired by the following projects:
About
🔧 Laravel + Symfony Serializer. This package provides a bridge between Laravel and Symfony Serializer.
Topics
Resources
License
Code of conduct
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors2
Uh oh!
There was an error while loading.Please reload this page.
