Symfony - How to transfrom these 2 functions in DRY way?

Viewed 31

I got a service where I got 2 functions doing a part where the same Repository is called but with different queries and different arguments passed.

Basically, I have this first function:

public function function1($date, Entity1 $entity1)
{
    $repos = $this->em->getRepository(EntityCommon::class)->findAllByXXX($entity1, $date);
    ...//Operations unique to this function
    $results = new functionDRY(); //part common to both starting with the foreach on $repos
}

and this second function:

public function function2($date, Entity2 $entity2)
{
    $repos = $this->em->getRepository(EntityCommon::class)->findAllByYYY($entity2, $date);
    ...//Operations unique to this function
    $results = new functionDRY(); //part common to both starting with the foreach on $repos
}

I wanted to create a third function where I would use DRY logic since a big chunk of code would be similar except in the query needed in the repository:

public function functionDRY()
{
    foreach ($repos as $repo) {// only operations common to both
        $somethings = $repo->getSomething()->getValues();
        foreach ($somethings as $something) {
        }
    }
}

How could I write the 3rd method since on I use foreach on $repos but it's defined in the 2 other functions?

Also, I tried to call the functionDRY in the 2 first functions but it doesn't work. I tried using directly functionDRY() but it didn't work either. How can I call the function in both function1 and function2?

That might be rookie mistakes I would avoid in the future.

1 Answers

You may want to reverse your logic. The sample below would use the method AService::functionDRY for both entities and the method gets $repos from the appropriate function1 or function2 based on the class of the entity.

class AService
{
  public function function1($date, Entity1 $entity1)
  {
    $repos = $this->em->getRepository(EntityCommon::class)->findAllByXXX($entity1, $date);
    //Operations unique to this function

    return $repos;
  }

  public function function2($date, Entity2 $entity2)
  {
    $repos = $this->em->getRepository(EntityCommon::class)->findAllByYYY($entity2, $date);
    //Operations unique to this function

    return $repos;
  }

  public function functionDRY($date, $entity)
  {
    $repos = [];
    if (is_a($entity, Entity1::class)) {
      $repos = $this->function1($date, $entity);
    }
    elseif (is_a($entity, Entity2::class)) {
      $repos = $this->function2($date, $entity);
    }

    foreach ($repos as $repo) {// only operations common to both
      $somethings = $repo->getSomething()->getValues();
      foreach ($somethings as $something) {
      }
    }
  }
}
Related