php – 序列化程序Symfony上的回调
发布时间:2020-12-13 13:45:07 所属栏目:PHP教程 来源:网络整理
导读:我正在运行Symfony 2.7,我正在尝试输出一个对象(Doctrine实体)作为 JSON. 当我正在标准化对象时,我想转换它的一些值.要做到这一点,我在the documentation中找到了“setCallbacks”方法,但我对如何将它应用于我的案例感到有点困惑. 有没有办法在调用Symfonys
|
我正在运行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服务 我认为在你的场景中,情况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: AppBundleDateTimeNormalizer
tags:
- { name: serializer.normalizer }
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
