Symfony2 is a powerful php framework, backed by doctrine ORM. MongoDB uses a JSON/BSON-storage for its documents.
While using SF2 for REST/JSON requests, JSON exports of DB objects is often required. There are many ways to achieve that from an ORM PoV:
- manual one by creating a toJson() and fromJson() methods for each Entity/Document
- use a serializer
In SF2, I do recommend JMSSerializerBundle : it is simple to install, thanks to Composer, and very easy to use.
For example, to encode data within the controller:
$serializer = JMS\Serializer\SerializerBuilder::create()->build(); $jsonContent = $serializer->serialize($data, 'json');
At this point, $jsonContent is a String. And to send it as an answer:
$response = new Response($jsonContent); $response->headers->set('Content-Type', 'application/json'); return $response;
And that’s all.
To be a little bit more efficient, we can create a new “JsonResponse” class
namespace AB3\ExampleBundle\Internal; use Symfony\Component\HttpFoundation\Response; class JsonResponse extends Response { public static function create($jsonContent) { $response = new Response($jsonContent); $response->headers->set('Content-Type', 'application/json'); return $response; } }
From my daily usage, I’d rather put this ‘create’ method directly in a Root Controller that all my controllers extends, in order to simply common stuffs…
namespace AB3\ExampleBundle\Controller; use Symfony\Component\HttpFoundation\Response; class ARootController extends Controller { public function sendJsonOk($data) { $serializer = JMS\Serializer\SerializerBuilder::create()->build(); $jsonContent = $serializer->serialize($data, 'json'); $response = new Response($jsonContent); $response->headers->set('Content-Type', 'application/json'); return $response; } }
Then, the call is quite simply for any action into a controller
class MyController extends ARootController { public function exampleAction() { $data = ....; // get some datas to send back to user return $this->sendJsonOk($data); } }