I previously wrote a similar topic but I would suggest you to use this option because its profiler flow for running queries and persistence operations tend to be simpler and lighter on system resources. Also the RegistryInterface gives us ability to reset entity manager in case of infamous "closed entity" issues.


Repository


namespace App\Repository;

use App\Entity\User;
use Symfony\Bridge\Doctrine\RegistryInterface;

class UserRepository implements UserRepositoryInterface
{
private $objectRepository;
private $entityManager;

public function __construct(RegistryInterface $registry)
{
$this->objectRepository = $registry->getRepository(User::class);
$this->entityManager = $registry->getManagerForClass(User::class);
}

public function findWhatever(): array
{
return $this->objectRepository
->createQueryBuilder('u')
->getQuery()
->getResult();
}

public function persistWhatever(): void
{
$this->entityManager->persist(new User());
$this->entityManager->flush();
}
}

The RegistryInterface comes with methods below if you need them.


Array
(
[0] => __construct
[1] => getDefaultEntityManagerName
[2] => getEntityManager
[3] => getEntityManagers
[4] => resetEntityManager
[5] => getEntityNamespace
[6] => getAliasNamespace
[7] => getEntityManagerNames
[8] => getEntityManagerForClass
[9] => getName
[10] => getConnection
[11] => getConnectionNames
[12] => getConnections
[13] => getDefaultConnectionName
[14] => getDefaultManagerName
[15] => getManager
[16] => getManagerForClass
[17] => getManagerNames
[18] => getManagers
[19] => getRepository
[20] => resetManager
)

Just for your info, if you wonder, there are many more ways of using repositories such as listed below (just a few).


use Doctrine\ORM\EntityManagerInterface;

class UserRepository implements UserRepositoryInterface
{
private $objectRepository;
private $entityManager;

public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
$this->objectRepository = $this->entityManager->getRepository(User::class);
}
}

use Doctrine\Common\Persistence\ManagerRegistry;

class UserRepository implements UserRepositoryInterface
{
private $objectRepository;
private $entityManager;

public function __construct(ManagerRegistry $managerRegistry)
{
$this->objectRepository = $managerRegistry->getRepository(User::class);
$this->entityManager = $managerRegistry->getManager();
}
}

use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;

class UserRepository extends ServiceEntityRepository implements UserRepositoryInterface
{
public function __construct(RegistryInterface $registry)
{
parent::__construct($registry, User::class);
}
}

use Doctrine\ORM\EntityRepository;

class UserRepository implements UserRepositoryInterface
{
private $entityRepository;

public function __construct(EntityRepository $entityRepository)
{
$this->entityRepository = $entityRepository;
}
}