A
A
Anton Medvedev2011-08-21 14:59:51
PHP
Anton Medvedev, 2011-08-21 14:59:51

Working with Doctrine ORM: Custom Repositories?

I have about 10 entities: \App\Entity\User, \App\Entity\Group,…
Each of them has its own repositories: \App\Repository\UserRepository,… Each has a dozen methods.
The Doctrine uses the following method to access them:

$userRepository = $em->getRepository('App\Entity\User');

However, this is not convenient, because missing code completion.
Question: how to properly organize work with repositories without increasing the static coherence of the code?
Should I use a static get method?
class UserRepository extends EntityRepository
{
    /**
     * @static
     * @return \App\Repository\UserRepository
     */
    public static function get()
    {
        $em = \Registry::getInstance()->get('em');
        return $em->getRepository('App\Entity\User');
    }
}

I watched how the work with the doctrine is implemented in the symphony, but there is the same problem with code completion.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
N
nekufa, 2011-08-21
@nekufa

If I need a complete code, then I can add a line
use App\Repository\UserRepository;
$userRepository = $em->getRepository('App\Entity\User');
$userRepository instanceof UserRepository;

C
casey, 2011-08-21
@casey

I also suffered from a similar problem - but I did not find a beautiful solution. A static method is not very good, comments are too, instanceof litters the code. Stopped on the comments as suggested.

P
patashnik, 2011-08-21
@patashnik

Methods in controller?

// somewhere in controller
private function getEntityManager()
{
    return \Registry::getInstance()->get('em');
}
/**
 * @return \App\Repository\UserRepository
 */
private function getUserRepository()
{
    return $getEntityManager()->getRepository('App\Entity\User');
}

K
kastigar, 2011-08-22
@kastigar

I don't see anything wrong with a static get method. IMHO, in your case, this is the best option:
- performance should not be inferior or much inferior to direct access via EM
- no need to worry about code clutter
- accessibility of the method from any scripts / classes
Yes, PHP is such a language, code completion is very often not available. Personally, I often used instanceofas a temporary solution. Those. as soon as completion is needed, I add instanceof. After the function is completed, I remove it. Not the most ideal solution, but in most cases it was enough. For doctrine repositories would do with a static get method.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question