Symfony2 Use Doctrine in Service Container

后端 未结 8 498
猫巷女王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:27

    For Symfony 3.x

    The most easy-peasy solution for me was to just turn on autowiring/autoconfiguring, and then injecting the service I needed via the constructor. Note that I have also allowed any controller to be injected as a service by setting resource: '../../src/AppBundle/*'

     #services.yml or config.yml
     services:
        _defaults:
            autowire: true
            autoconfigure: true
            public: false
        # Allow any controller to be used as a service
        AppBundle\:
            resource: '../../src/AppBundle/*'    
            # you can exclude directories or files
            # but if a service is unused, it's removed anyway
            exclude: '../../src/AppBundle/{Entity,Repository,Tests,DataFixtures,Form}'
    

    Then in any service, you can inject & use the entity manager $em (or any other service/controller) via the constructor like this:

    // class xyz
    private $em;
    // constructor
    public function __construct(\Doctrine\ORM\EntityManager $em)  {
        $this->em = $em;
    }
    public function bar() {
        //Do the Database stuff
        $query = $this->em->createQueryBuilder();
        //Your Query goes here
        $result = $query->getResult();
    }
    

提交回复
热议问题