在我的Symfony 3应用程序中,我使用规范化器和序列化程序将结果集格式化为
JSON.默认情况下,所有教条日期时间都以以下格式呈现:
"maintenanceStart":{ "timezone":{"name":"Australia\/Melbourne","location":{"country_code":"AU","latitude":-37.81667,"longitude":144.96666,"comments":"Victoria"}},"offset":36000,"timestamp":1372892400}
我可以通过在规范化器上设置回调,以每个字段为基础输出ISO日期格式,如下所示:
$callback = function ($dateTime) { return $dateTime instanceof \DateTime ? $dateTime->format ( \DateTime::ISO8601 ) : ''; }; $normalizer->setCallbacks ( array ( 'maintenanceStart' => $callback ) );
但我想将此更改应用于所有时间戳,而无需指定每个字段.有一种直截了当的方法吗?
实体定义:
/** * @var \DateTime * * @ORM\Column(name="MAINTENANCE_START",type="datetime",nullable=true) */ private $maintenanceStart;
控制器代码:
public function dataAction(Request $request) { $doc = $this->get ( 'doctrine' ); $repo = $doc->getRepository ( 'AppBundle:Customer' ); $result = $repo->createQueryBuilder ( 'c' )->getQuery ()->getResult (); $encoder = new JsonEncoder (); $normalizer = new GetSetMethodNormalizer (); $callback = function ($dateTime) { return $dateTime instanceof \DateTime ? $dateTime->format ( \DateTime::ISO8601 ) : ''; }; $normalizer->setCallbacks ( array ( 'maintenanceStart' => $callback ) ); $serializer = new Serializer ( array ( $normalizer,new \AppBundle\DateTimeNormalizer() ),array ( $encoder ) ); $json = $serializer->serialize ( $result,'json' ); return $this->render ( 'default/data.json.twig',[ 'data' => $json,'base_dir' => realpath ( $this->getParameter ( 'kernel.root_dir' ) . '/..' ) ] ); }
在尝试遵循规定的方法(在这里发布
https://stackoverflow.com/a/33149890/403614)时,我忽略了观察到传递给Serializer的规范化器数组是依赖于顺序的.
原文链接:https://www.f2er.com/php/240269.html因此,我上面的代码的问题和修复是颠倒顺序,以便DateTime Normalizer首先应用:
$normalizer = new GetSetMethodNormalizer (); $serializer = new Serializer ( array ( new \AppBundle\DateTimeNormalizer(),$normalizer ),array ( $encoder ) );