S
S
symnoob2020-08-09 23:07:35
symfony
symnoob, 2020-08-09 23:07:35

Symfony - Repository How to avoid duplicate code in this case?

Hello everyone,
How to avoid double code in this case?

Each Repository has this code, only of course type hinting is always different

public function save(User $user): void
    {
        $this->getEntityManager()->persist($user);
        $this->getEntityManager()->flush();
    }


I would like to create some kind of abstract class for this business, but what about type hinting?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2020-08-10
@symnoob

flush()you need to take it out, because you can persist 100 objects and make one flush - one series of calls to the database. In your case, there will be 100 or more calls to the database
. To make a universal method for a persister in repositories, since you have decided to do this (many people consider this to be true), you can make a universal code (trait, for example), in which there will be a check through classMetadata, that the object being saved is of the required type for the repository (here we do not forget about the inheritance of entities, is_a()and that's it) and if the wrong object comes - throw InvalidArgumentException
BUT!If you host repositories in your own domain/package/namespace, then you can't avoid code duplication, and it's not that scary... Coupling and inheritance web is scarier. Repositories are still few in all code relative to the entire codebase.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question