【发布时间】:2016-01-19 14:53:34
【问题描述】:
我正在关注 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 method is not recognized....知道为什么...? 我该如何解决这个问题。
【问题讨论】:
-
你错过了显而易见的事情。 $this->em 在你的构造函数中设置,所以删除 $this->em = $this->getDoctrine()->getManager();一切都会好起来的。
标签: php symfony doctrine-orm