Last Updated: February 25, 2016
·
464
· vojtech-dobes

Independent EntityRepository in Doctrine 2

So you want your repository as independent service, without special treatment and getting via getRepository() method? It's not that difficult. Lets introduce our abstract independent ancestor:

abstract class IndependentEntityRepository extends Doctrine\ORM\EntityRepository
{
    public function __construct(Doctrine\ORM\EntityManager $em)
    {
        $metadata = $em->getClassMetadata($this->getEntityClass());
        parent::__construct($em, $metadata);
    }

    abstract public function getEntityClass();
}

And now we can define our specific repository, that can be instantiated anywhere and requires just EntityManager instance. No dependency on EntityManager::getRepository() anymore.

class ArticlesRepository extends IndependentEntityRepository
{
    public function getEntityClass()
    {
        return Article:: CLASS; // this syntax is available since PHP 5.5
    }
}