【发布时间】:2014-02-18 09:51:33
【问题描述】:
我正在尝试使用 EntityManager 从自定义类中的实体获取数据,但出现此错误
错误:在第 28 行调用非对象上的成员函数 get()
我不知道为什么$this->container 没有子元素,我正在扩展ContainerAware...
这是我的代码
<?php
namespace WhiteBear\UsersBundle\Security;
use Symfony\Component\Security\Core\Role\RoleInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\DependencyInjection\ContainerAware;
use WhiteBear\CustomerPortalBundle\Entity\VtigerContactdetails;
use WhiteBear\CustomerPortalBundle\Entity\VtigerContactscf;
class UserDependentRole extends ContainerAware implements RoleInterface
{
private $user;
public function __construct(UserInterface $user)
{
$this->user = $user;
}
public function getRole()
{
$rol = $this->getEntityManager()->getRepository('WhiteBearCustomerPortalBundle:VtigerContactscf')
->findBy(array(
'contactid' => $this->user->getId()
));
$role = $rol['groups'] == '1' ? "AGENT" : "USER";
return 'ROLE_' . strtoupper($role);
}
public function getEntityManager() {
return $this->container->get('doctrine')->getEntityManager();
}
}
编辑也尝试通过 services.yml 仅注入教义2
<?php
namespace WhiteBear\UsersBundle\Security;
use Symfony\Component\Security\Core\Role\RoleInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\ORM\EntityManager;
use WhiteBear\CustomerPortalBundle\Entity\VtigerContactdetails;
use WhiteBear\CustomerPortalBundle\Entity\VtigerContactscf;
class UserDependentRole implements RoleInterface
{
private $user;
private $em;
public function __construct(UserInterface $user, EntityManager $em)
{
$this->user = $user;
$this->em = $em;
}
public function getRole()
{
$rol = $this->em->getRepository('WhiteBearCustomerPortalBundle:VtigerContactscf')
->findBy(array(
'contactid' => $this->user->getId()
));
$role = $rol['groups'] == '1' ? "AGENT" : "USER";
return 'ROLE_' . strtoupper($role);
}
}
services.yml
services:
white_bear.userdepend:
class: WhiteBear\CustomerPortal\Security\UserDependentRole
arguments: [@doctrine.orm.entity_manager]
但是当我从实体调用这个类时,我收到了这个错误
可捕获的致命错误:参数 2 传递给 WhiteBear\UsersBundle\Security\UserDependentRole::__construct() 必须 是 Doctrine\ORM\EntityManager 的一个实例,没有给出
那是因为我从我的实体中这样做,因为我不知道如何让 EntityManager 解析到构造函数中......
/**
* @inheritDoc
*/
public function getRoles() {
return array(new UserDependentRole($this));
}
【问题讨论】: