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

Symfony serializer bridge for Spiral Framework

License

NotificationsYou must be signed in to change notification settings

spiral-packages/symfony-serializer

Repository files navigation

PHP Version RequireLatest Stable VersionphpunitpsalmTotal Downloads

This package provides an extension to the default list of serializers in Spiral Framework, allowing you to easilyserialize and deserialize objects into various formats such asJSON,XML,CSV, andYAML.

NoteRead more about spiral/serializer component in theofficialdocumentation.

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

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

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

You can install the package via composer:

composer require spiral-packages/symfony-serializer

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

protectedconstLOAD = [// ...    \Spiral\Serializer\Symfony\Bootloader\SerializerBootloader::class,];

NoteBootloaderSpiral\Serializer\Bootloader\SerializerBootloader can be removed.If you are usingspiral-packages/discoverer,you don't need to register bootloader by yourself.

Configuration

The package comes with default configurations fornormalizers,encoders, andmetadataLoader. However, you canchange these configurations based on your project's requirements.

There are two ways to configure the package:

Config file

You can create a configuration fileapp/config/symfony-serializer.php and definenormalizers,encoders,andSymfony\Component\Serializer\Mapping\Loader\LoaderInterfaceforSymfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory used by the Symfony Serializer componentparameters to extend the default configuration.

Here is an example of the configuration file:

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

Bootloader

Spiral\Serializer\Symfony\EncodersRegistryInterface andSpiral\Serializer\Symfony\NormalizersRegistryInterfaceprovided by the package to add your own normalizers or encoders. You can register your ownnormalizers orencodersusing theregister method provided by these interfaces.

Here is an example:

namespaceApp\Application\Bootloader;useSpiral\Serializer\Symfony\EncodersRegistryInterface;useSpiral\Serializer\Symfony\NormalizersRegistryInterface;useSpiral\Boot\Bootloader\Bootloader;finalclass AppBootloaderextends Bootloader{publicfunctionboot(NormalizersRegistryInterface$normalizersRegistry,EncodersRegistryInterface$encodersRegistry,    ):void {// Add CustomNormalizer before ObjectNormalizer$normalizersRegistry->register(normalizer:newCustomNormalizer(), priority:699);$encodersRegistry->register(newCustomEncoder());    }}

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.

WarningTheyaml 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.

Here are several ways to use these serializers:

1. Set a default serializer

You can set a desired Symfony serializer as the default application serializer by settingtheDEFAULT_SERIALIZER_FORMAT environment variable.

DEFAULT_SERIALIZER_FORMAT=symfony-json

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

Serialization:

useSpiral\Serializer\SerializerInterface;useApp\Repository\PostRepository;finalclass PostController{publicfunction__construct(privatereadonlySerializerInterface$serializer,privatereadonlyPostRepository$repository,    ) {}publicfunctionshow(string$postId):string    {$post =$this->repository->find($postId);return$this->serializer->serialize($post);    }}

Deserialization:

useApp\Entity\Post;useSpiral\Serializer\SerializerInterface;finalclass PostService{publicfunction__construct(privatereadonlySerializerInterface$serializer,privatereadonlyHttpClient$http,    ) {}publicfunctionshow(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

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

Serialization:

useSpiral\Serializer\SerializerManager;useSpiral\Serializer\SerializerInterface;useApp\Repository\PostRepository;finalclass PostController{privatereadonlySerializerInterface$serializer;publicfunction__construct(SerializerManager$manager,privatereadonlyPostRepository$repository,    ) {$this->serializer =$manager->getSerializer('symfony-json');    }publicfunctionshow(string$postId):string    {$post =$this->repository->find($postId);return$this->serializer->serialize($post);    }}

Deserialization:

useApp\Entity\Post;useSpiral\Serializer\SerializerInterface;finalclass PostService{privatereadonlySerializerInterface$serializer;publicfunction__construct(SerializerManager$manager,privatereadonlyHttpClient$http,    ) {$this->serializer =$manager->getSerializer('symfony-json');    }publicfunctionshow(string$postId):Post    {$json =$this->http->get('https://example.com/posts/' .$postId);return$this->serializer->unserialize($json, Post::class);    }}

Alternatively, you can use theserialize andunserialize methods of the manager class:

usePsr\Container\ContainerInterface;useSpiral\Serializer\SerializerManager;useApp\Repository\PostRepository;useApp\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

You can also use the Symfony Serializer directly by requesting theSymfony\Component\Serializer\SerializerInterfacefrom the container. Once you have the serializer, you can use it toserialize anddeserialize objects.

Here's an example:

useSymfony\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

Symfony Serializer Manager provides additional methods to work with data:

  • normalize: This method takes indata and aformat and returns a value that represents the normalized data. Thecontext parameter can also be passed to control the normalization process.

  • denormalize: This method takes indata, atype, aformat, and acontext, and returns an object thatrepresents the denormalized data.

  • supportsNormalization: This method takes indata, aformat, and acontext, and returns abooleanindicating whether the given data can be normalized by the serializer.

  • supportsDenormalization: This method takes indata, atype, aformat, and acontext, and returns aboolean indicating whether the given data can be denormalized by the serializer.

  • encode: This method takes indata, aformat, and acontext, and returns astring that represents theencoded data.

  • decode: This method takes indata, aformat, and acontext, and returns avalue that represents thedecoded data.

  • supportsEncoding: This method takes in aformat and acontext, and returns aboolean indicating whether thegiven format can be used to encode data by the serializer.

  • supportsDecoding: This method takes in aformat and acontext, and returns aboolean indicating whether thegiven format can be used to decode data by the serializer.

useSpiral\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 certainscenarios.

Testing

composertest

Changelog

Please seeCHANGELOG for more information on what has changed recently.

License

The MIT License (MIT). Please seeLicense File for more information.

About

Symfony serializer bridge for Spiral Framework

Topics

Resources

License

Stars

Watchers

Forks

Contributors4

  •  
  •  
  •  
  •  

Languages


[8]ページ先頭

©2009-2025 Movatter.jp