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

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (97)

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

该代码只会导致错误消息“Fatal error: Call to undefined method ...::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);
    }
}

services.yml

service:
    site:
        class: ...\Service\Site
提问于
用户回答回答于

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

//services.yml
  your service here:
    class: yourclasshere
    arguments: [@doctrine.orm.entity_manager]

在类上:

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();
  }
}
用户回答回答于

以下是一个例子config.yml

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

扫码关注云+社区

领取腾讯云代金券