-
-
Save weaverryan/790ad99d2fdb6d4a1c06 to your computer and use it in GitHub Desktop.
JSON Product endpoint
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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