Doctrine 2 : Custom repositories and inheritance

本秂侑毒 提交于 2019-12-11 05:00:38

问题


Hello Stack Overflowers,

Working with Doctrine 2, I encounter some troubles regarding custom repositories and inheritance.

Long story short, I want to make that kind of structure :

  • BaseEntityRepository : contains generic methods such as findByXXX() based on called class name
  • SomeEntityRepository : contains specific methods related to the entity type

The code for those classes looks like this :

BaseEntityRepository :

namespace model\repositories;

use \Doctrine\ORM\EntityRepository;

class BaseEntityRepository extends EntityRepository {
    public function findByID($id) {
        $result = null;

        try {
            $dql = "SELECT a FROM " . get_called_class() . " a WHERE a.id = :id";
            $query = $this->_em->createQuery($dql);
            $query->setParameter("id", $id);
            $result = $query->getSingleResult();
        } catch (\Exception $ex) {
            echo $ex->getMessage();
        }

        return $result;
    }
}

SomeEntityRepository :

namespace model\repositories;

class SomeEntityRepository extends BaseEntityRepository {

}

My test sample code :

$repo = $em->getRepository("model\\entities\\SomeEntity");
$result = $repo->findByID($id);

With this code, I expect $repo to have access to the findByID($id) method by inheritance from BaseEntityRepository. Of course, the repositoryClass annotation for SomeEntity targets SomeEntityRepository. On the contrary, BaseEntityRepository is NOT targeted as a standalone repository class.

The thing is, all I get is an exception :

Class "model\repositories\SomeEntityRepository" sub class of "model\repositories\BaseEntityRepository" is not a valid entity or mapped super class.

I can't, for the sake of me, figure out what's wrong in this code. Maybe I missed something but my research towards inheritance in repositories did not bring any satisfying results. I guess there is some kind of restriction on repositories such as for them to work properly, all should be targeted as repositoryClass at least once or something like that, but that doesn't please me.

If you have any kind of insight, piece of advice or bits of solution, I'm all ears! Thanks again.


回答1:


The problem lies with get_called_class which is not going to do what you want.

Use the doctrine query builder. That eliminates the need to know the specific entity class.

Search for: Querying for Objects Using Doctrine's Query Builder

http://symfony.com/doc/current/book/doctrine.html



来源:https://stackoverflow.com/questions/23781592/doctrine-2-custom-repositories-and-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!