0

How do I query the mySql DB? For some reason I am not getting the response I expect below.

I have a message table with a messageBody column that I would like to get.

I am also trying to return it as an array of JSON formatted objects.

/**
 * @Route("/api/messages")
 * @Template()
 */
public function messagesGetAction()
{

    $repository = $this->getDoctrine()->getRepository('AppBundle:Message');
    $messagesArr = $repository->findBy(array('messageBody'=>'messageBody'));
    $messages = json_encode($messagesArr);

    return new Response($messages);

}

This is what is returned

[{},{},{}]

My question is how do I build a proper get controller to return an api json response?

Message entity

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="message")
 */
class Message
{

    /**
     * @var integer
     */
    private $id;

    /**
     * @var string
     */
    private $fromUser;

    /**
     * @var string
     */
    private $toUser;

    /**
     * @var string
     */
    private $messageTitle;

    /**
     * @var string
     */
    private $messageBody;


    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set fromUser
     *
     * @param string $fromUser
     * @return Message
     */
    public function setFromUser($fromUser)
    {
        $this->fromUser = $fromUser;

        return $this;
    }

    /**
     * Get fromUser
     *
     * @return string 
     */
    public function getFromUser()
    {
        return $this->fromUser;
    }

    /**
     * Set toUser
     *
     * @param string $toUser
     * @return Message
     */
    public function setToUser($toUser)
    {
        $this->toUser = $toUser;

        return $this;
    }

    /**
     * Get toUser
     *
     * @return string 
     */
    public function getToUser()
    {
        return $this->toUser;
    }

    /**
     * Set messageTitle
     *
     * @param string $messageTitle
     * @return Message
     */
    public function setMessageTitle($messageTitle)
    {
        $this->messageTitle = $messageTitle;

        return $this;
    }

    /**
     * Get messageTitle
     *
     * @return string 
     */
    public function getMessageTitle()
    {
        return $this->messageTitle;
    }

    /**
     * Set messageBody
     *
     * @param string $messageBody
     * @return Message
     */
    public function setMessageBody($messageBody)
    {
        $this->messageBody = $messageBody;

        return $this;
    }

    /**
     * Get messageBody
     *
     * @return string 
     */
    public function getMessageBody()
    {
        return $this->messageBody;
    }
}

Routing

## api routes
app_getmessages: 
  pattern: /api/messages
  defaults: { _controller: AppBundle:Default:messages}

Database

enter image description here

NEW CODE:

/**
 * @Route("/api/messages")
 * @Template()
 */
public function messagesGetAction()
{

    $repository = $this->getDoctrine()->getRepository('XYGamingBundle:Message');
    $messagesArr = $repository->findAll();
    $json = new JsonResponse($messagesArr);

    if (!$json) {
        throw $this->createNotFoundException(
            'No messages found'
        );
    }

    return new Response($json);

}

Solution

// add to controller
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;

/**
 * @Route("/api/messages")
 * @Template()
 */
public function messagesGetAction()
{

    //$serializer = $container->get('jms_serializer');
    // $serializer->serialize($data, $format);
    // $data = $serializer->deserialize($inputStr, $typeName, $format);

    $encoders = array(new XmlEncoder(), new JsonEncoder());
    $normalizers = array(new GetSetMethodNormalizer());
    $serializer = new Serializer($normalizers, $encoders);

    $repository = $this->getDoctrine()->getRepository('XYGamingBundle:Message');
    $data = $repository->findAll();

    //$json = $serializer->serialize($data, 'json');

    $json = $serializer->serialize($data, 'json');

    //$json = new JsonResponse($messagesArr);

    if (!$json) {
        throw $this->createNotFoundException(
            'No messages found'
        );
    }

    return new Response($json);

}

Thanks guys

1 Answer 1

2

Here it seems the problem happens in the json_encode part, because json_encode does not know how to access your private property, nor it knows how to use the getter.

For this you can use the Symfony serializer Documentation for it or the JMSSerializer Bundle (if you're building a complex API, you will sooner or later needs it)

Also you can use the new JsonResponse($yourObject) that would do the json_encode for you , as well as setting properly the HTTP headers (otherwise if you use Response , your json will still be advertized by the browser as being text/html )

Sign up to request clarification or add additional context in comments.

4 Comments

Awesome but even this is returning empty $messagesArr = $repository->findAll(); I was going to change it to that.
Awesome, I will check that out, FYI JsonResponse reuturns HTTP/1.0 200 OK Cache-Control: no-cache Content-Type: application/json Date: Sun, 31 May 2015 05:34:08 GMT "[{},{},{}]" still empty let me check out the bundle suggested
I installed the Symfony Serializer and I am still having an empty response? Let me update the OP with new code
NVM I got it will update OP. I write on node.js, php is okay but not very fun. I have to do this for a small project. Thanks though man you're awesome.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.