Symfony2 在服务容器中使用 Doctrine [英] Symfony2 Use Doctrine in Service Container

查看:23
本文介绍了Symfony2 在服务容器中使用 Doctrine的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I use Doctrine in a service container?

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

The Code just causes an error message "Fatal error: Call to undefined method ...::get()".

<?php

namespace ...Service;

use DoctrineORMEntityManager;
use ...EntityHeader;

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

services.yml

service:
    site:
        class: ...ServiceSite

推荐答案

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

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.

如果您还没有注入 EntityManager,请阅读 这个.

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

更新:

您需要让容器将 EntityManager 注入到您的服务中.这是在 config.yml 中执行此操作的示例:

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: YourVendorYourBundleServiceYourService
        arguments: [ @doctrine.orm.entity_manager ]

我更喜欢定义 将服务捆绑在它们自己的 services.yml 文件中,但这有点高级,因此使用 config.yml 就足够开始了.

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.

这篇关于Symfony2 在服务容器中使用 Doctrine的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆