Symfony2在服务容器中使用Doctrine

use*_*510 55 doctrine symfony

如何在服务容器中使用Doctrine?

代码只会导致错误消息"致命错误:调用未定义的方法...... :: get()".

<?php

namespace ...\Service;

use Doctrine\ORM\EntityManager;
use ...\Entity\Header;

class dsdsf
{ 
    protected $em;

    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    public function create()
    {
        $id = 10;
        $em = $this->get('doctrine')->getEntityManager();
        $em->getRepository('...')->find($id);
    }
}
Run Code Online (Sandbox Code Playgroud)

services.yml

service:
    site:
        class: ...\Service\Site
Run Code Online (Sandbox Code Playgroud)

Eln*_*mov 85

根据你的代码,你已经EntityManager注入了.你不需要打电话$em = $this->get('doctrine')->getEntityManager()- 只需使用$this->em.

如果你没有注射EntityManager,请阅读此内容.

更新:

您需要让容器注入EntityManager您的服务.以下是一个示例config.yml:

services:
    your.service:
        class: YourVendor\YourBundle\Service\YourService
        arguments: [ @doctrine.orm.entity_manager ]
Run Code Online (Sandbox Code Playgroud)

我更喜欢在自己的文件中定义 bundle的服务services.yml,但这有点高级,所以使用config.yml就足够好了.

  • 最好是每次都传递Doctrine并调用getEntityManager,因为实体管理器在数据库级错误之后关闭.因此,如果您想在已知的事务失败后手动执行操作,那就搞砸了. (2认同)

小智 9

要轻松访问Entitymanager,请使用以下命令:

//services.yml
  your service here:
    class: yourclasshere
    arguments: [@doctrine.orm.entity_manager]
Run Code Online (Sandbox Code Playgroud)

在课堂上:

class foo
{
  protected $em;



  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();
  }
}
Run Code Online (Sandbox Code Playgroud)

这是我的第一个答案,所以任何评论都赞赏:)

  • 您发布的示例类不是有效的PHP.纠正你的榜样,我会给你一个upvote. (7认同)
  • 你错过了2个半冒号 (2认同)