dongmei9508 2013-11-05 19:24
浏览 33
已采纳

Symfony2并避免过于冗长的代码

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

  • 写回答

2条回答 默认 最新

  • doufei8250 2013-11-05 22:02
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站