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
    }
}Written by Vojtěch Dobeš
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
 #Php 
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#

 
 
 
 
