Search code examples
jsonajaxsymfonyjsonserializerserialization

Symfony2 - entities with relationships as json response


I am trying to create efficient JSON Response controllers for AJAX. So far, instead of passing whole entity to JsonResponse I am creating arrays with necessary data inside where I can easily manage output data leaving less work for JavaScript. My action looks something like this:

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);
}

It is all good, ajax is working fast.

At this point I started googling searching if this is a right approach to it. I found out about JMSSerializerBundle which serializes entities. I tried using it, but I am facing problems serializing relationships and how to access related entities data using JS. It is so complicated leaving so many proccessing to do for JS that I start doubting that it is a good approach.

What do you think? What is your experience with it? Which approach is better and why?


Solution

  • I prefer the symfony normalizer/serializer approach. http://symfony.com/doc/current/components/serializer.html As described, you can overide serializer to serialize your object in the same custom way for your whole application

    enter image description here