Question

I'm trying to set up a json example using symfony2.
I've created a test bundle, a test entity ("Message"), set up the orm etc
The Message (table) has the following columns: id, title, text
I'm trying to expose a route */mydomain/message that would expose a json interface to messages table (a small list)

The first methodology I tried was:

Create a MessageController class that uses Symfony\Component\HttpFoundation\Response and has a function like this:

public function testAction() {  
    $response = new Response(json_encode(**code_req_here**));  
    return $response;  
}

and set a route like so:

test:  
    pattern: /test  
    defaults: { _controller: myProjectmyTestBundle:Message:test, _format: json}  
    requirements: { _format: (xml|json), _method: GET }  
  1. is this a correct methodology?
  2. what do I put on the code_req_here?

the second methodology I tried was by using the FOS/RestBundle but didn't manage to complete the guide correctly as I understand, so

  1. please provide a small guide on how to do (just) this with FOS/RestBundle
Was it helpful?

Solution

is this a correct methodology?

Yes I like it but I would modify the routing rule a bit like this:

test:
    pattern: /test.{_format}
    defaults: { _controller: myProjectmyTestBundle:Message:test, _format: json}
    requirements: { _format: (xml|json), _method: GET }

what do I put on the code_req_here?

Put the array that you want to convert to json format. ex. array(array('id' => 1, 'value' => 'test'), array('id' => 2, 'value' => 'smart'))

OTHER TIPS

I recommend using

http://jmsyst.com/bundles/JMSSerializerBundle

$serializer = $container->get('jms_serializer');
$serializer->serialize($data, 'json'); // json|xml|yml
$data = $serializer->deserialize($inputStr, $typeName, $format);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top