Symfony2 Use Doctrine in Service Container

后端 未结 8 501
猫巷女王i
猫巷女王i 2020-12-08 12:59

How do I use Doctrine in a service container?

The Code just causes an error message \"Fatal error: Call to undefined method ...::get()\".



        
8条回答
  •  情歌与酒
    2020-12-08 13:46

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

    Your code would change like this.

    1. Service configuration

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

    2. Create new class - custom repository:

    use Doctrine\ORM\EntityManagerInterface;
    
    class YourRepository
    { 
        private $repository;
    
        public function __construct(EntityManagerInterface $entityManager)
        {
            $this->repository = $entityManager->getRepository(YourEntity::class);
        }
    
        public function find($id)
        {
            return $this->repository->find($id);
        }
    }
    

    3. Use in any Controller or Service like this

    class dsdsf
    { 
        private $yourRepository;
    
        public function __construct(YourRepository $yourRepository)
        {
            $this->yourRepository = $yourRepository;
        }
    
        public function create()
        {
            $id = 10;
            $this->yourRepository->find($id);
        }
    }
    

    Do you want to see more code and pros/cons lists?

    Check my post How to use Repository with Doctrine as Service in Symfony.

提交回复
热议问题