我試圖使用的EntityManager從我的自定義類內的實體獲取數據,但我得到這個錯誤Symfony2的ContainerAware未能得到元素
Error: Call to a member function get() on a non-object on line 28
我不知道爲什麼$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注入doctrine2
<?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]
但正如我打電話從實體這個班,我得到這個錯誤
Catchable Fatal Error: Argument 2 passed to WhiteBear\UsersBundle\Security\UserDependentRole::__construct() must be an instance of Doctrine\ORM\EntityManager, none given
這因爲從我的實體我這樣做,因爲我不知道如何讓EntityManager解析成構造函數...
/**
* @inheritDoc
*/
public function getRoles() {
return array(new UserDependentRole($this));
}
這樣做是對我的services.yml什麼都不做,得到了同樣的錯誤:( –
好吧,檢查更新,並請考慮我的迴應的「而是」一節。 –
是啊,這是我第一次嘗試,但我失敗了,請參閱我的錯誤更新只是一個愚蠢的事情,但我不知道如何從類調用者(在這種情況下,實體)設置EntityManager構造函數 –