Symfony2注入entityManager错误

时间:2016-01-19 14:53:34

标签: php symfony doctrine-orm

我正在遵循Doctrine ORM Symfony2 Documentation。说到持久化对象到数据库我得到这个错误:

Attempted to call an undefined method named "getDoctrine" of class "BooksApi\BookBundle\Controller\IndexController".

我在代码中做的唯一不同的是我正在尝试将EntityManager创建为服务....

的services.xml:

<?xml version="1.0" encoding="UTF-8"?>
<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
    <services>
        <service id="booksapi.controller.index"
                 class="BooksApi\BookBundle\Controller\IndexController">
            <argument type="service" id="booksapi.repositories.test_repository" />
            <argument type="service" id="doctrine.orm.entity_manager" />
        </service>
    </services>
</container> 

我的索引控制器:

<?php

namespace BooksApi\BookBundle\Controller;

use BooksApi\BookBundle\Entity\BooksEntity;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpFoundation\Response;


class IndexController
{
    /**
     * @var EntityManager
     */
    public $em;

    /**
     *  @param EntityManager $entityManager
     */
    public function __construct(
        EntityManager $entityManager
    ){
        $this->em = $entityManager;
    }

    /**
     * @return Response
     */
    public function testAction()
    {

        $book = new BooksEntity();
        $book->setTitle('Tomazi in da Jungle');
        $book->setPrice('19.99');
        $book->setDescription('Lorem ipsum dolor');

        $this->em = $this->getDoctrine()->getManager();

        $this->em->persist($book);
        $this->em->flush();

        return new Response('Created product id '.$book->getId());
    }
}

所以看错误getDoctrine方法无法识别....任何想法为什么......? 我该如何解决这个问题。

2 个答案:

答案 0 :(得分:3)

1 /快速解决方案:

删除此行:$this->em = $this->getDoctrine()->getManager();

2 /更好的解决方案:

IndexController应扩展Controller

Symfony\Bundle\FrameworkBundle\Controller\Controller

可以使用getDoctrine方法。通过这种方式,Doctrine Entity Manager不需要注入。没有构造函数,没有服务定义。

答案 1 :(得分:3)

定义你的控制器是一个很好的做法所以我会坚持这一点。这里有两件事似乎错了:

  1. 您的服务定义(services.xml)包含两个参数,您的Controller构造函数只接受一个参数。

  2. 这一行:$this->em = $this->getDoctrine()->getManager();:您根本不需要它,因为您的$this->em已在构造函数中定义,其值为EntityManager实例。只需删除此行即可,

  3. 您收到此错误的原因仅仅是因为您尝试使用getDoctrine方法作为Controller方法。 does只是要求Container创建EntityManager的实例,因为您已将此实例注入constructor,因此不需要此调用(getDoctrine)在所有