Question

In most of my controllers, I need to get a reference to one or more of my custom entity repositories, so naturally, I do this a lot:

/** @var $repo MyFirstEntityRepository */
$repo1 = $this->getDoctrine()->getManager()->getRepository('MyNamespaceMyBundle:MyFirstEntity');
/** @var $repo MySecondEntityRepository */
$repo2 = $this->getDoctrine()->getManager()->getRepository('MyNamespaceMyBundle:MySecondEntity');
/** @var $repo MyThirdEntityRepository */
$repo3 = $this->getDoctrine()->getManager()->getRepository('MyNamespaceMyBundle:MyThirdEntity');

My question is: if I have a bunch of different Entities that I need a repository reference for, is it good practice to create a bunch of corresponding get[EntityName]Repository methods in some sort of BaseController which all other controllers could inherit from?

The refactored controller code would be more like:

$repo1 = $this->getMyFirstEntityRepository();
$repo2 = $this->getMySecondEntityRepository();
$repo3 = $this->getMyThirdEntityRepository();

Which would play nicely with IDE autocompletion and type inference as well.

Is this good practice? Or does it violate some sort of standard? Does it make the code any less "loosely coupled"?

Was it helpful?

Solution

How about this?

$em = $this->getDoctrine()->getManager();
/** @var $repo MyFirstEntityRepository */
$repo1 = $em->getRepository('MyNamespaceMyBundle:MyFirstEntity');
/** @var $repo MySecondEntityRepository */
$repo2 = $em->getRepository('MyNamespaceMyBundle:MySecondEntity');
/** @var $repo MyThirdEntityRepository */
$repo3 = $em->getRepository('MyNamespaceMyBundle:MyThirdEntity');

Seems to me declaring variable $em solves all the DRY violations...

OTHER TIPS

I'd suggest the Model Manager approach. You could then, in turn, use the JMSDiExtraBundle to make instantiation even easier.

Note: If you're using Symfony 2.2, then you probably already have the JMSDiExtraBundle installed, since it was part of the standard distribution in that version.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top