Skip to content

Instantly share code, notes, and snippets.

@weaverryan
Last active August 29, 2015 14:02
Show Gist options
  • Select an option

  • Save weaverryan/790ad99d2fdb6d4a1c06 to your computer and use it in GitHub Desktop.

Select an option

Save weaverryan/790ad99d2fdb6d4a1c06 to your computer and use it in GitHub Desktop.
JSON Product endpoint
<?php
// URL: http://bit.ly/dcon-sf-json
// src/DrupalCon/FirstBundle/Controller/ProductController.php
use Symfony\Component\HttpFoundation\Response;
// ...
class ProductController extends Controller
{
// copy this function (and comments) to the TOP of your existing ProductController class
/**
* Finds and displays a Product entity.
*
* @Route("/products/{id}.json", name="product_show_json")
* @Method("GET")
*/
public function showJsonAction($id)
{
$em = $this->getDoctrine()->getManager();
/** @var Product $product */
$product = $em->getRepository('FirstBundle:Product')->find($id);
if (!$product) {
throw $this->createNotFoundException('Unable to find Product entity.');
}
$data = array(
'id' => $product->getId(),
'name' => $product->getName(),
'price' => $product->getPrice(),
);
$json = json_encode($data);
return new Response($json);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment