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

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

问题描述

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



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

 <?php 

命名空间... \Service;

请使用Doctrine\ORM\EntityManager;
使用... \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


解决方案

根据您的代码,您已经有一个 EntityManager $ em = $ this-> get('doctrine') - > getEntityManager() - 只需使用 $如果您没有注入 EntityManager



,请阅读



更新:



您需要使容器将 EntityManager 注入您的服务。以下是在 config.yml 中执行此操作的示例:

 服务: 
your.service:
class:YourVendor\YourBundle\Service\YourService
arguments:[@ doctrine.orm.entity_manager]
/ pre>

我更喜欢在他们自己的 services.yml 文件中定义捆绑服务,但这是一个更高级的,所以使用 config.yml 足够开始。


How do I use Doctrine in a service container?

The Code just causes an error message "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

解决方案

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.

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

UPDATE:

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: YourVendor\YourBundle\Service\YourService
        arguments: [ @doctrine.orm.entity_manager ]

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服务容器中的使用原则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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