Symfony2 - 关系为 json 响应的实体

Symfony2 - entities with relationships as json response

我正在尝试为 AJAX 创建高效的 JSON 响应控制器。到目前为止,我不是将整个实体传递给 JsonResponse,而是在其中创建包含必要数据的数组,我可以在其中轻松管理输出数据,从而减少 JavaScript 的工作量。我的操作看起来像这样:

public function getOffersAction(Request $request)
{
    if (!$request->isXmlHttpRequest()) {
        return new JsonResponse(array('message' => 'You can access this only using Ajax!'), 400);
    }

    /** @var OfferRepository $offerRepository */
    $offerRepository = $this->getDoctrine()->getRepository('IndexBundle:Offer');
    $offers = $offerRepository->findBy(array('state' => 'available'));

    $offersArray = array();
    /** @var Offer $offer */
    foreach ($offers as $offer) {
        $areasArray = array();
        foreach ($offer->getAreas() as $area) {
            $areasArray[] = array(
                'name' => $area->getName()
            );
        }

        $offersArray[] = array(
            'id'        => $offer->getId(),
            'code'      => $offer->getCode(),
            'title'     => $offer->getTitle(),
            'city'      => $offer->getCity(),
            'country'   => $offer->getCountry()->getName(),
            'latitude'  => $offer->getLatitude(),
            'longitude' => $offer->getLongitude(),
            'areas'     => $areasArray
        );
    }

    return new JsonResponse($offersArray, 200);
}

一切都很好,ajax 工作很快。

此时我开始谷歌搜索这是否是正确的方法。我发现了 JMSSerializerBundle 序列化实体。我尝试使用它,但我在序列化关系以及如何使用 JS 访问相关实体数据时遇到问题。为 JS 留下如此多的处理工作是如此复杂,以至于我开始怀疑这是不是一个好方法。

你怎么看?您对此有何体验?哪种方法更好,为什么?

我更喜欢 symfony normalizer/serializer 方法。 http://symfony.com/doc/current/components/serializer.html 如前所述,您可以覆盖序列化程序以针对整个应用程序以相同的自定义方式序列化您的对象