How to call Entity Manager in a constructor?

前端 未结 6 1578
终归单人心
终归单人心 2020-12-06 05:52

I\'ve been trying to call Entity Manager in a constructor:

function __construct()
{
    $this->getDoctrine()->getEntityManager();
    ...
         


        
6条回答
  •  爱一瞬间的悲伤
    2020-12-06 06:40

    You need to make a service for your class and pass the doctrine entity manager as the argument doctrine.orm.entity_manager.Like in services.yml

    services:
      test.cutom.service:
        class:  Test\YourBundleName\Yourfoldernameinbundle\Test
        #arguments:
        arguments: [ @doctrine.orm.entity_manager  ] 
            #entityManager: "@doctrine.orm.entity_manager"
    

    You must import your services.yml in config.yml

    imports:
        - { resource: "@TestYourBundleName/Resources/config/services.yml" }
    

    Then in your class's constructor get entity manager as argument

    use Doctrine\ORM\EntityManager;
    Class Test {
    
      protected $em;
    
      public function __construct(EntityManager $entityManager)
      {
        $this->em = $entityManager;
      }
    }
    

    Hope this makes sense

提交回复
热议问题