How to configure dependency injection for repository class in symfony 3

后端 未结 3 420
温柔的废话
温柔的废话 2020-12-19 04:51

Symfony generator generated the following class of repository:

namespace AppBundle\\Repository;
use AppBundle\\Entity\\GroupEntity;

/**
 * GroupEntityReposi         


        
3条回答
  •  囚心锁ツ
    2020-12-19 05:42

    Since Symfony 3.4 you can avoid factory and use a TagRepository service that extends ServiceEntityRepository class instead of directly EntityRepository.

    use AppBundle\Entity\GroupEntity;
    use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
    use Symfony\Bridge\Doctrine\RegistryInterface;
    
    class GroupEntityRepository extends ServiceEntityRepository
    {
        public function __construct(RegistryInterface $registry)
        {
            parent::__construct($registry, GroupEntity::class);
        }
    }
    

    With this method, your service would be automatically registered with autowiring feature.

    You can also do better in all Symfony version by using composition over inheritance.

    final class GroupEntityRepository
    {
        /** @var EntityManagerInterface */
        private $entityManager;
    
        /** @var ObjectRepository */
        private $objectRepository;
    
        public function __construct(EntityManagerInterface $entityManager)
        {
            $this->entityManager = $entityManager;
            $this->objectRepository = $this->entityManager->getRepository(GroupEntity::class);
        }
    

    This service can also be autowiring. You can go further by respecting the SOLID principle and create an interface. There is a good explanation in this article (Repository Pattern in Symfony)

提交回复
热议问题