Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine many repository for same entity

is it possible to have two repositories for the same entity ?

I try something like that, but it does not work..

class PackageRepository extends EntityRepository
{
    public function __construct($em, Mapping\ClassMetadata $class)
    {
        $cmf = $em->getMetadataFactory();
        $class = $cmf->getMetadataFor('Product');
        parent::__construct($em, $class);
    }
}

Any ideas ?

like image 650
Charles Avatar asked Feb 22 '23 05:02

Charles


2 Answers

First of all, why would you want to do that?

Second, to answer your question. You can have as many repositories working with same entities as you like, they are just simple classes after all.

But you can link only one class with the entity class using the @Repository annotation (or YAML, or XML, whatever). All the mapping data is stored in the EntityManager. EntityManager will know only one repository class is linked with the entity class, if you try to get it with $entity->getReposiotry() or similar it will return only the linked class.

But nothing can stop you from creating your own classes which do some queries and call them directly, explicitly, without relying on the EntityManagers repository mapping.

like image 105
ZolaKt Avatar answered Feb 27 '23 22:02

ZolaKt


I also have run into the same issue, when two Symfony bundles work with same entity, but queries are different for each bundle, so I also decided create separate repository for each bundle. For Doctrine 2 the solution can be:

  1. "@Repository annotation" can be used to point default repository or just avoid it.
  2. Create usual repository class, e.g. "MyEntityRepository".
  3. In code:

    $myEntityRepo = new MyEntityRepository($entityManager, $entityManager->getClassMetadata('AppBundle:MyEntity'));

like image 37
Molarro Avatar answered Feb 27 '23 23:02

Molarro