I have several routes that start with /experiment/{id}/...
and I'm tired of rewriting the same logic to retrieve the signed in user's experiment. I guess I could refactor my code but I'm guessing @ParamConverter
would be a better solution.
How would I rewrite the following code to take advantage of Symfony's @ParamConverter functionality?
/**
* Displays details about an Experiment entity, including stats.
*
* @Route("/experiment/{id}/report", requirements={"id" = "\d+"}, name="experiment_report")
* @Method("GET")
* @Template()
* @Security("has_role('ROLE_USER')")
*/
public function reportAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$experiment = $em->getRepository('AppBundle:Experiment')
->findOneBy(array(
'id' => $id,
'user' => $this->getUser(),
));
if (!$experiment) {
throw $this->createNotFoundException('Unable to find Experiment entity.');
}
// ...
}
Experiment entities have composite primary keys as follows:
class Experiment
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
*/
protected $id;
/**
* @var integer
*
* @ORM\Column(name="user_id", type="integer")
* @ORM\Id
*/
protected $userId;
/**
* @ORM\ManyToOne(targetEntity="UserBundle\Entity\User", inversedBy="experiments", cascade={"persist"})
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
protected $user;
// ..
}
I want to retrieve a signed in user's experiment using their user id
and an experiment id
in the route.
You can achieve that by using custom ParamConverter
. For example something like that:
namespace AppBundle\Request\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use AppBundle\Entity\Experiment;
class ExperimentConverter implements ParamConverterInterface
{
protected $em;
protected $user;
public function __construct(EntityManager $em, TokenStorage $tokenStorage)
{
$this->em = $em;
$this->user = $tokenStorage->getToken()->getUser();
}
public function apply(Request $request, ParamConverter $configuration)
{
$object = $this->em->getRepository(Experiment::class)->findOneBy([
'id' => $request->attributes->get('id'),
'user' => $this->user
]);
if (null === $object) {
throw new NotFoundHttpException(
sprintf('%s object not found.', $configuration->getClass())
);
}
$request->attributes->set($configuration->getName(), $object);
return true;
}
public function supports(ParamConverter $configuration)
{
return Experiment::class === $configuration->getClass();
}
}
You need to register your converter service and add a tag to it:
# app/config/config.yml
services:
experiment_converter:
class: AppBundle\Request\ParamConverter\ExperimentConverter
arguments:
- "@doctrine.orm.default_entity_manager"
- "@security.token_storage"
tags:
- { name: request.param_converter, priority: 1, converter: experiment_converter }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With