我想实现一些服务,我做的第一件事就是将私有$em定义为实体管理器,如下所示:
<?php
namespace Users'UsersBundle'Services;
use Doctrine'ORM'EntityManager;
use Symfony'Component'HttpKernel'Exception'NotFoundHttpException;
use Usuarios'UsersBundle'Entity'User;
/**
* Class UserManager
*/
class UserManager
{
private $em;
/**
* @param EntityManager $em
*/
public function __construct(EntityManager $em)
{
$this->$em = $em;
}
}
在同一类中使用 EntityManager 的函数示例:
/**
* Find all posts for a given author
*
* @param User $author
*
* @return array
*/
public function findPosts(User $author)
{
$posts = $this->$em->getRepository('BlogBundle:Post')->findBy(array(
'author' => $author
)
);
return $posts;
}
但是,当我调用任何函数(例如上面显示的函数)时,我会收到以下错误:可捕获的致命错误:类 Doctrine''ORM''EntityManager 的对象无法转换为字符串。
我确实导入了该服务。我错过了什么?提前感谢您的支持。
$this->$em
应该是:
$this->em
$this->$em 尝试将$em转换为对象时的字符串。除非对象定义了 __toString() 方法,否则将出现异常。
取而代之的是:
$posts = $this->$em->getRepository('BlogBundle:Post')->findBy(array(
'author' => $author
试试这个:
$posts = $this->em->getRepository('BlogBundle:Post')->findBy(array(
'author' => $author
请注意,我从 $this->$em 更改为 $this->em。