- Notifications
You must be signed in to change notification settings - Fork1
Symfony serializer bridge for Spiral Framework
License
spiral-packages/symfony-serializer
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
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.
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
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,];
NoteBootloader
Spiral\Serializer\Bootloader\SerializerBootloadercan be removed.If you are usingspiral-packages/discoverer,you don't need to register bootloader by yourself.
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:
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')];
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()); }}
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.
WarningThe
yamlencoder requires thesymfony/yamlpackage and is disabled when the package is not installed.Install thesymfony/yamlpackage and the encoder will be automatically enabled.
Here are several ways to use these serializers:
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); }}
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');
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);
Symfony Serializer Manager provides additional methods to work with data:
normalize: This method takes in
dataand aformatand returns a value that represents the normalized data. Thecontext parameter can also be passed to control the normalization process.denormalize: This method takes in
data, atype, aformat, and acontext, and returns an object thatrepresents the denormalized data.supportsNormalization: This method takes in
data, aformat, and acontext, and returns abooleanindicating whether the given data can be normalized by the serializer.supportsDenormalization: This method takes in
data, atype, aformat, and acontext, and returns abooleanindicating whether the given data can be denormalized by the serializer.encode: This method takes in
data, aformat, and acontext, and returns astringthat represents theencoded data.decode: This method takes in
data, aformat, and acontext, and returns avaluethat represents thedecoded data.supportsEncoding: This method takes in a
formatand acontext, and returns abooleanindicating whether thegiven format can be used to encode data by the serializer.supportsDecoding: This method takes in a
formatand acontext, and returns abooleanindicating 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.
composertestPlease seeCHANGELOG for more information on what has changed recently.
The MIT License (MIT). Please seeLicense File for more information.
About
Symfony serializer bridge for Spiral Framework
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Contributors4
Uh oh!
There was an error while loading.Please reload this page.