我正在创建一个正规化器,我不确定它是否应该应用。
“自定义规范化器和/或编码器也可以通过标记为serializer.normalizer和serializer.encoder来加载。还可以设置标签的优先级以确定匹配顺序。”
https://symfony.com/doc/current/serializer.html#adding-normalizers-and-encoders
services.yml
datetime_normalizer:
class: App\Normalizer\DateTimeNormalizer
public: true
tags: [serializer.normalizer]班级
<?php
namespace App\Normalizer;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
/**
* Class DateTimeNormalizer
*/
class DateTimeNormalizer implements NormalizerInterface
{
/**
* {@inheritdoc}
*/
public function normalize($object, $format = null, array $context = array())
{
return $object->format(\DateTime::ISO8601);
}
/**
* {@inheritdoc}
*/
public function supportsNormalization($data, $format = null)
{
return $data instanceof \DateTime;
}
}打电话
$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$normalizer = new ObjectNormalizer($classMetadataFactory);
$serializer = new Serializer([$normalizer]);
$user = $serializer->normalize($token->getUser());输出
"datetime":{"timezone":{"name":"UTC","transitions":[{"ts":-9223372036854775808,"time":"-292277022657-01-27T08:29:52+0000","offset":0,"isdst":false,"abbr":"UTC"}],"location":{"country_code":"??","latitude":0,"longitude":0,"comments":""}},"offset":0,"timestamp":1527033600}github的完整代码
https://github.com/ricardosaracino/symfony-pull-list/blob/master/config/services.yaml
发布于 2018-08-21 12:27:12
与创建自己的序列化程序不同,您需要依赖Symfony创建的序列化程序,在需要的地方注入它。这方面的一个例子在doc:https://symfony.com/doc/current/serializer.html#using-the-serializer-service中。
看看https://symfony.com/doc/current/controller.html#fetching-services,让控制器了解更多信息。
https://stackoverflow.com/questions/51940574
复制相似问题