jeudi 12 octobre 2023

Static functions in Symfony Entities, while passing EntityManagerInterface?

I'm currently designing my own service using Symfony, Doctrine and MySQL. I have several Entities, which allow fast database interaction. The project is for creating and managing sports tournaments with group system and finals. For this I for example have the Matches.php Entity, which has the normal Entity structure. From there on I added several static and non-static functions, related to the Matches entity. Here are 2 examples:

// Non-static function for getting TeamB's points. 
public function getPointsTeamB(): int
{
    $score = $this->getScore();
    if($score["team_a"] < $score["team_b"]) return 3;
    if($score["team_a"] == $score["team_b"]) return 1;
    return 0;
}

// Static function to getting the next games in the match plan.
public static function getNext(EntityManagerInterface $entityManager, int $amount): array
{
    ->createQueryBuilder("m")
    ->select("m.id", "IDENTITY(m.team_a) AS team_a", "IDENTITY(m.team_b) AS team_b", "m.started_at", "m.ended_at", "m.paused_at", "m.paused_for")
    ->where("m.started_at is NULL AND m.ended_at is NULL")
    ->orderBy("m.id", "ASC")
    ->setMaxResults($amount)
    ->getQuery()
    ->getResult();
    return $entityManager->getRepository(Matches::class)
}

I access these functions for example here:

#[Route('/ajax/matches/get_next/{amount}', name: 'app_ajax_match_get_next', requirements: ['match_id' => '\d+'], methods: ["GET"])]
    public function app_ajax_match_get_next(int $amount, RequestStack $requestStack, EntityManagerInterface $entityManager): Response
    {
        $req = RequirementsCheck::create($requestStack, $entityManager, permissions: [Permission::VIEW_DASHBOARD]);
        if(!$req->isAllowed()) return $req->getResponse();
        $matches = Matches::getNext($entityManager, $amount);
        return new JsonResponse(APISerializer::serializeDoctrineObjects($matches, $entityManager));
    }

As you can see I just use call the function using Matches::getNext()

Now I was talking to someone, who told me that I should rewrite my code because of this 'bad habit'. As you can see I pass the EntityManagerInterface whenever needed in the function. They said that Entities should primarily represent the data and state of an object and should not be tightly coupled with database-specific operations and that there will be Testing and Reusability issues. Is that true and if yes, where should I put these functions? Should I rewrite my code or just change my design next time?

Thanks in Advance :)

Aucun commentaire:

Enregistrer un commentaire