ServiceEntityRepository.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <?php
  2. namespace Doctrine\Bundle\DoctrineBundle\Repository;
  3. use Doctrine\ORM\EntityRepository;
  4. use Doctrine\Persistence\ManagerRegistry;
  5. use LogicException;
  6. use function sprintf;
  7. /**
  8. * Optional EntityRepository base class with a simplified constructor (for autowiring).
  9. *
  10. * To use in your class, inject the "registry" service and call
  11. * the parent constructor. For example:
  12. *
  13. * class YourEntityRepository extends ServiceEntityRepository
  14. * {
  15. * public function __construct(ManagerRegistry $registry)
  16. * {
  17. * parent::__construct($registry, YourEntity::class);
  18. * }
  19. * }
  20. *
  21. * @template T
  22. * @template-extends EntityRepository<T>
  23. */
  24. class ServiceEntityRepository extends EntityRepository implements ServiceEntityRepositoryInterface
  25. {
  26. /**
  27. * @param string $entityClass The class name of the entity this repository manages
  28. *
  29. * @psalm-param class-string<T> $entityClass
  30. */
  31. public function __construct(ManagerRegistry $registry, string $entityClass)
  32. {
  33. $manager = $registry->getManagerForClass($entityClass);
  34. if ($manager === null) {
  35. throw new LogicException(sprintf(
  36. 'Could not find the entity manager for class "%s". Check your Doctrine configuration to make sure it is configured to load this entity’s metadata.',
  37. $entityClass
  38. ));
  39. }
  40. parent::__construct($manager, $manager->getClassMetadata($entityClass));
  41. }
  42. }