Search code examples
phpsymfonycode-duplication

How to Reduce Code Duplication in Symfony2


I have 3 "main" entities : TypeA and TypeB linked to User by a ManyToOne relation.

I have 2 "secondary" entities : UserTypeA and UserTypeB, which contain the attributes of the ManyToOne relations (for example, the comment a user has assigned to a product of type A). These two entities and their repository are similar (except that one is linked to TypeA and the other to TypeB).

Here is a part of my code :

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);

   //...
}

As you can see, I need to duplicate each action to make them work with each entity. Is there any way to combine these actions ? Same question about the secondary entities and their repositories.

Thanks.


Solution

  • Create a service class that performs the logic and takes say, the user type as a parameter.