Answer the question
In order to leave comments, you need to log in
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');
class UserRepository extends EntityRepository
{
/**
* @static
* @return \App\Repository\UserRepository
*/
public static function get()
{
$em = \Registry::getInstance()->get('em');
return $em->getRepository('App\Entity\User');
}
}
Answer the question
In order to leave comments, you need to log in
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;
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
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');
}
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 instanceof
as 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 questionAsk a Question
731 491 924 answers to any question