You want to create an alternate way to serve your data from your controllers on a Symfony2 project.
How about adding one event listener to convert to JSON anything that is sent from a controller. To do this, your project has to have your controllers to return arrays of Doctrine2 Entities and also to leverage @Template
and @Route
.
If you already do, only insert this EventListener and ensure you have a dependency or two met (below). Note that except the Serializer, the other ones are not required, you would need to manually create the services in your project (not covered here).
To use, try cURL to a controller
For example, Imagine you have an endpoint at /api/feed
, When you use your web browser, you get your basic HTML version.
When using Content-Type: application/json
, you get a JSON representation.
curl -H 'Content-Type: application/json' http://localhost:8000/app_dev.php/api/feed/
Created with Symfony2 2.4, "symfony/symfony-standard".
"jms/serializer-bundle": "~0.13"
See the Serializer Annotations documentation on how to use on your entities.
For this example to work by cut-and-paste, at least.
"jms/di-extra-bundle": "~1.4"
I love this extension! It allows to use annotations in your services to define them. See the DiExtra bundle documentation for details.
Create a file and adjust paths to suit your project namespaces.