我正在运行Symfony 2.7,我正在尝试输出一个对象(Doctrine实体)作为
JSON.
当我正在标准化对象时,我想转换它的一些值.要做到这一点,我在the documentation中找到了“setCallbacks”方法,但我对如何将它应用于我的案例感到有点困惑.
有没有办法在调用Symfonys序列化服务器时设置的规范化器上调用“setCallbacks”方法?
这是我正在努力实现的一个简短示例:
//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序列化器.看起来好像内置的序列化程序应该能够处理我想要实现的内容.
默认的Serializer服务是在依赖项注入阶段创建的,而Serializer接口不允许编辑(完全)检索规范化程序.
我想你在这里有(至少)三种选择:
>将自定义规范化程序添加到默认的Serializer服务
>将NormalizableInterface添加到您的实体
>按照您的尝试创建新的Serializer服务(或文档建议的本地对象).
我认为在你的场景中,情况1是首选(因为2变得很无聊很快).
我会做这样的事情;首先创建一个自定义规范化器
<?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,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'); } }
然后将其注册到您的服务:
# app/config/services.yml services: datetime_normalizer: class: AppBundle\DateTimeNormalizer tags: - { name: serializer.normalizer }