Skip to content

Instantly share code, notes, and snippets.

@merltron-pa
Last active January 26, 2022 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save merltron-pa/0381d5c855dfca759925a83a50c1cfe7 to your computer and use it in GitHub Desktop.
Save merltron-pa/0381d5c855dfca759925a83a50c1cfe7 to your computer and use it in GitHub Desktop.
Final, Entire controller for JMS article
<?php
namespace App\Controller;
use App\Entity\Address;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use FOS\RestBundle\Controller\AbstractFOSRestController;
class AddressController extends AbstractFOSRestController
{
private EntityManagerInterface $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
/**
* @Route("/address", methods={"POST"})
* @ParamConverter("address", converter="fos_rest.request_body")
*/
public function postAddress(Address $address): Response
{
// Normally, you would validate the data before persisting it.
// For simplicity, we have left this step out.
$this->em->persist($address);
$this->em->flush();
return $this->handleView($this->view($address));
}
/**
* @Route("/address/{id}", methods={"GET"})
*/
public function getAddress(string $id): Response
{
$address = $this->em->find(Address::class, $id);
if (empty($address)) {
throw $this->createNotFoundException('The address does not exist');
}
return $this->handleView($this->view($address));
}
/**
* @Route("/address/{id}", methods={"DELETE"})
*/
public function deleteAddress(string $id): Response
{
$address = $this->em->find($id, Address::class);
if (empty($address)) {
throw $this->createNotFoundException('The address does not exist');
}
$this->em->remove($address);
$this->em->flush();
return new Response(null, 200);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment