如何减少Symfony2中的代码重复

时间:2014-11-05 15:03:49

标签: php symfony code-duplication

我有3个“主要”实体: TypeA TypeB 通过ManyToOne关系链接到用户

我有2个“辅助”实体: UserTypeA UserTypeB ,其中包含ManyToOne关系的属性(例如,用户已分配给产品的评论) A)类型。这两个实体及其存储库是相似的(除了一个链接到TypeA而另一个链接到TypeB)。

以下是我的代码的一部分:

public function typea_commentAction(TypeA $typea)
{
   $user = $this->getUser();
   $userTypeA = $this->getDoctrine()
                      ->getManager()
                      ->getRepository('GamUserBundle:UserTypeA')
                      ->getComment($user, $typea);

   //...
}

public function typeb_commentAction(TypeB $typeb)
{
   $user = $this->getUser();
   $userTypeB = $this->getDoctrine()
                      ->getManager()
                      ->getRepository('GamUserBundle:UserTypeB')
                      ->getComment($user, $typeb);

   //...
}

如您所见,我需要复制每个操作以使它们与每个实体一起使用。有没有办法结合这些行动?关于次要实体及其存储库的相同问题。

感谢。

1 个答案:

答案 0 :(得分:3)

创建一个执行逻辑的服务类,并将用户类型作为参数。