Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting the Doctrine Entity Manager in services - Bad practice?

Using https://insight.sensiolabs.com to scan / check my code, I get the following warning:

The Doctrine Entity Manager should not be passed as an argument.

Why is it such a bad practice to inject the Entity Manager in a service? What is a solution?

like image 385
Machiel Avatar asked Dec 19 '13 12:12

Machiel


2 Answers

With respect to the comment that repositories cannot persist entities.

class MyRepository extends EntityRepository
{
    public function persist($entity) { return $this->_em->persist($entity); }
    public function flush  ()        { return $this->_em->flush  (); }

I like to make my repositories follow more or less a "standard" repository interface. So I do:

interface NyRepositoryInterface
[
    function save($entity);
    function commit();
}
class MyRepository extends EntityRepository implements MyRepositoryInterface
{
    public function save  ($entity) { return $this->_em->persist($entity); }
    public function commit()        { return $this->_em->flush  (); }

This allows me to define and inject non-doctrine repositories.

You might object to having to add these helper functions to every repository. But I find that a bit of copy/paste is worth it. Traits might help here as well.

The idea is move away from the whole concept of an entity manager.

like image 119
Cerad Avatar answered Oct 10 '22 10:10

Cerad


I am working on a quite a large project currently and have recently started following the approach with repositories that can mutate data. I don't really understand the motivation behind having to inject EntityManager as a dependency which is as bad as injecting ServiceManager to any class. It is just a bad design that people try to justify. Such operations like persist, remove and flush can be abstracted into sth like AbstractMutableRepository that every other repository can inherit from. So far it has been doing quite well and makes code more readable and easier to unit test! Show me at least one example of a service that has EM injected and unit test for it looked correctly? To be able to unit test sth that has EM injected is more about testing implementation than anything else. What happens is then you end up having so many mocks set up for it, you cannot really call it a decent unit test! It is a code coverage hitter, nothing more!

like image 35
user3647324 Avatar answered Oct 10 '22 11:10

user3647324