Symfony2 Use Doctrine in Service Container

后端 未结 8 512
猫巷女王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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 13:52

    According to your code, you already have an EntityManager injected. You don't need to call $em = $this->get('doctrine')->getEntityManager() — just use $this->em.

    If you don't inject an EntityManager already, read this.

    UPDATE:

    You need to make the container inject an EntityManager into your service. Here's an example of doing it in config.yml:

    services:
        your.service:
            class: YourVendor\YourBundle\Service\YourService
            arguments: [ @doctrine.orm.entity_manager ]
    

    I prefer to define bundles' services in their own services.yml files, but that's a bit more advanced, so using config.yml is good enough to get started.

提交回复
热议问题