0

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?

Ignas Damunskis
  • 1,515
  • 1
  • 17
  • 44
  • Have you considered using [Fractal](http://fractal.thephpleague.com/)? It's a good middle ground between JMSSerializer and manually building the JSON array in your controllers. – dchesterton Dec 06 '16 at 11:50
  • 2
    what is your problem while using JMSSerializerBundle ? this bundle really works like a charm most of the time – VaN Dec 06 '16 at 12:00
  • You could also make your entities serialize able. That would make it easier then your approach now if i may say so. An example of a serialize able User entity can be found here: http://symfony.com/doc/current/security/entity_provider.html#create-your-user-entity – Frank B Dec 06 '16 at 13:19

1 Answers1

0

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

goto
  • 7,908
  • 10
  • 48
  • 58