Symfony 4 DateTimeNormalizer服务未应用

时间:2018-08-21 01:52:37

标签: php symfony symfony4

我正在创建规范化器,我不确定现在应该应用它

“还可以通过将自定义规范化器和/或编码器标记为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

1 个答案:

答案 0 :(得分:3)

您需要依赖Symfony创建的序列化程序,而不是创建自己的序列化程序,只需将其注入所需的位置即可。例如:https://symfony.com/doc/current/serializer.html#using-the-serializer-service

请查看https://symfony.com/doc/current/controller.html#fetching-services,以使控制器了解更多信息。