Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

🔧 Laravel + Symfony Serializer. This package provides a bridge between Laravel and Symfony Serializer.

License

NotificationsYou must be signed in to change notification settings

wayofdev/laravel-symfony-serializer

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 


WayOfDev Logo

Build
Build Status

Project
Total DownloadsLatest Stable VersionCommits since latest releasePHP Version Require

Quality
CodecovMutation testing badgePHP Stan Level 6 of 9

Community
DiscordFollow 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 theirofficial page.


🗂️ Table of Contents


🤔 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:

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"

🔧 Configuration

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,];

→ Configuration Options

  • default: Specifies the default serializer format. This can be overridden by setting theSERIALIZER_DEFAULT_FORMAT environment variable. The default issymfony-json.
  • debug: Enables debug mode forProblemNormalizer. This can be set using theSERIALIZER_DEBUG_MODE environment variable. It defaults to theAPP_DEBUG value.
  • 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\AttributeLoader is used.

→ Custom Strategies

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.

Normalizer Registration Strategy

To create a custom normalizer registration strategy:

  1. Implement theNormalizerRegistrationStrategy interface:

    <?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    {// ...    }}
  2. Changeserializer.php config to use your custom strategy:

    'normalizerRegistrationStrategy' => CustomNormalizerRegistrationStrategy::class,

Encoder Registration Strategy

To create a custom encoder registration strategy:

  1. Implement theEncoderRegistrationStrategy interface:

    <?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()];        }    }}
  2. Changeserializer.php config to use your custom strategy:

    '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

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.

→ Components

SerializerManager

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

ResponseFactory

TheResponseFactory 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 underlyingSerializerManager
  • Serializer — To access the bound and configured original Symfony Serializer instance.

→ Example DTO

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;    }}

→ UsingSerializerManager in Service Classes

<?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']]        );    }}

→ UsingResponseFactory in Laravel Controllers

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);    }}

→ 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:

<?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);    }}

🔒 Security Policy

This project has asecurity policy.


🙌 Want to Contribute?

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.

Conventional Commits


🫡 Contributors

Contributors Badge

🌐 Social Links


📜 License

License


🧱 Credits and Useful Resources

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

Stars

Watchers

Forks

Sponsor this project

    Packages

    No packages published

    Contributors2

    •  
    •  

    [8]ページ先頭

    ©2009-2025 Movatter.jp