【发布时间】:2017-06-29 13:47:00
【问题描述】:
我正在构建一个 API,它需要将一些实体输出为 JSON。我试图弄清楚是否最好将实体规范化并将其传递给JsonResponse,或者我是否应该将其序列化并将其传递给Response。两者有什么区别?
/**
* Returning a Response
*/
public function getEntityAction($id)
{
$entity = $this->getDoctrine()->getRepository(MyEntity::class)->find($id);
$json = $this->get('serializer')->serialize($entity);
$response = new Response($json);
$response->headers->set('Content-Type', 'application/json');
return $response
}
/**
* Returning a JsonResponse.
*/
public function getEntityAction($id)
{
$entity = $this->getDoctrine()->getRepository(MyEntity::class)->find($id);
$array = $this->get('serializer')->normalize($entity);
return new JsonResponse($array);
}
除了我不必为JsonResponse 手动设置Content-Type 标头之外,两者之间是否有任何实际区别?
【问题讨论】: