v-c-dq
Last Updated: February 25, 2016
·
281
· vojtech-dobes
9b5416ee5575bb905e1fb1bcd02eabc3

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
    }
}
Say Thanks
Respond