回调序列化器Symfony [英] Callback on serializer Symfony

查看:33
本文介绍了回调序列化器Symfony的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行Symfony 2.7,并尝试将对象(Doctrine实体)输出为JSON.

I'm running Symfony 2.7 and I'm trying output an object (Doctrine entity) as JSON.

当我规范化对象时,我想转换它的一些值.为此,我在文档,但我对如何将其应用于我的案例感到很困惑.

When I'm normalizing the object I want to convert some of it's values. To do this I found the "setCallbacks" method in the documentation but I'm kinda stumped on how to apply it to my case.

在调用Symfonys序列化程序服务时设置的规范化器上,有什么方法可以调用"setCallbacks"方法吗?

Is there any way to call the "setCallbacks" method on the normalizer that is set when calling Symfonys serializer service?

这是我要实现的目标的简短示例:

Here is a short example of what I'm trying to achieve:

//ExampleController.php

public function getJSONOrderByIdAction($id) {
    $serializer = $this->get('serializer');
    $normalizer = $serializer->getNormalizer(); // <- This is what I'm unable to do

    $dateTimeToString = function ($dateTime) {
        return $dateTime instanceof \DateTime ? $dateTime->format(\DateTime::ISO8601) : '';
    };

    $normalizer->setCallbacks(['time' => $dateTimeToString]);


    $order = $this->getDoctrine()->find("AppBundle:Order", $id);

    return new JsonResponse(["order" => $serializer->normalize($order, null, ["groups" => ["public"]])]);
}

我知道大多数人都已切换到JMS序列化器.似乎内置的序列化程序应该能够处理我要实现的目标.

I'm aware that most people have switched to the JMS serializer. It just seems as if the built in serializer should be able to handle what I'm trying to achieve.

推荐答案

默认的序列化程序服务是在依赖项注入阶段创建的,并且序列化程序接口不允许编辑(完全)归一化程序.

The default Serializer service is created during dependency injection phase, and the Serializer interface do not allow editing of (full) retrieval of normalizers.

我认为您至少有三个选择:

I think you have (at least) three choice here:

  1. 将自定义规范化器添加到默认的Serializer服务
  2. 向您的实体添加NormalizableInterface
  3. 按照您的尝试创建新的Serializer服务(或文档建议的本地对象).

我认为在您的情况下,情况1是首选的(因为2变得非常无聊).

I think in your scenario, case 1 is preferred (since 2 becomes boring pretty fast).

我会做这样的事情;首先创建一个自定义的Normalizer

I would do something like this; first create a custom Normalizer

<?php
namespace AppBundle; 

class DateTimeNormalizer extends SerializerAwareNormalizer implements NormalizerInterface, DenormalizerInterface
{
    /**
     * {@inheritdoc}
     */
    public function normalize($object, $format = null, array $context = array())
    {
        return $object->format(\DateTime::ISO8601);
    }

    /**
     * {@inheritdoc}
     */
    public function denormalize($data, $class, $format = null, array $context = array())
    {
        return new $class($data);
    }

    /**
     * Checks if the given class is a DateTime.
     *
     * @param mixed  $data   Data to normalize.
     * @param string $format The format being (de-)serialized from or into.
     *
     * @return bool
     */
    public function supportsNormalization($data, $format = null)
    {
        return $data instanceof \DateTime;
    }

    /**
     * Checks if the given class is a DateTime.
     *
     * @param mixed  $data   Data to denormalize from.
     * @param string $type   The class to which the data should be denormalized.
     * @param string $format The format being deserialized from.
     *
     * @return bool
     */
    public function supportsDenormalization($data, $type, $format = null)
    {
        $class = new \ReflectionClass($type);

        return $class->isSubclassOf('\DateTime');
    }
}

然后将其注册到您的服务中

Then register it to your services:

# app/config/services.yml
services:
    datetime_normalizer:
        class: AppBundle\DateTimeNormalizer
        tags:
            - { name: serializer.normalizer }

这篇关于回调序列化器Symfony的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆