Symfony 2 EntityManager injection in service

后端 未结 4 1077
栀梦
栀梦 2020-11-28 23:21

I\'ve created my own service and I need to inject doctrine EntityManager, but I don\'t see that __construct() is called on my service, and injection doesn\'t wo

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 23:59

    Since 2017 and Symfony 3.3 you can register Repository as service, with all its advantages it has.

    Check my post How to use Repository with Doctrine as Service in Symfony for more general description.


    To your specific case, original code with tuning would look like this:

    1. Use in your services or Controller

    userRepository = $userRepository;
        }
    
        public function getUser($userId)
        {
            return $this->userRepository->find($userId);
        }
    }
    

    2. Create new custom repository

    repository = $entityManager->getRepository(UserEntity::class);
        }
    
        public function find($userId)
        {
            return  $this->repository->find($userId);
        }
    }
    

    3. Register services

    # app/config/services.yml
    services:
        _defaults:
            autowire: true
    
        Test\CommonBundle\:
           resource: ../../Test/CommonBundle
    

提交回复
热议问题