Injecting dependency into entity repository

后端 未结 6 1501
有刺的猬
有刺的猬 2020-12-13 04:46

Is there a simple way to inject a dependency into every repository instance in Doctrine2 ?

I have tried listening to the loadClassMetadata event and usi

6条回答
  •  别那么骄傲
    2020-12-13 05:19

    I've just define my own RepositoryFactory class

    1. Create RepositoryFactory class and define service, for example my_service.orm_repository.robo_repository_factory, with include @service_container injection
    2. And add check and set container service, for instance:

      private function createRepository(EntityManagerInterface $entityManager, $entityName)
      {
          /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadata */
          $metadata = $entityManager->getClassMetadata($entityName);
          $repositoryClassName = $metadata->customRepositoryClassName
              ?: $entityManager->getConfiguration()->getDefaultRepositoryClassName();
      
          $result = new $repositoryClassName($entityManager, $metadata);
          if ($result instanceof ContainerAwareInterface) {
              $result->setContainer($this->container);
          }
          return $result;
      }
      
    3. Create compiler class

      public function process(ContainerBuilder $container)
      {
          $def = $container->getDefinition('doctrine.orm.configuration');
          $def->addMethodCall(
              'setRepositoryFactory', [new Reference('robo_doctrine.orm_repository.robo_repository_factory')]
          );
      }
      
    4. After that any EntityRepository with ContainerAwareInterface has @service_container

提交回复
热议问题