문제

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"?

도움이 되었습니까?

해결책

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...

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top