Symfony2 ContainerAware无法获取元素

时间:2014-02-18 09:51:34

标签: php class symfony service

我正在尝试使用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注入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]

但是当我从一个实体调用这个类时,我收到了这个错误

  

可捕获的致命错误:参数2传递给   WhiteBear \ UsersBundle \ Security \ UserDependentRole :: __ construct()必须   是Doctrine \ ORM \ EntityManager的实例,没有给出

那是因为从我的实体我这样做,因为我不知道如何让EntityManager解析成构造函数......

/**
 * @inheritDoc
 */
public function getRoles() {
    return array(new UserDependentRole($this));
}

1 个答案:

答案 0 :(得分:4)

您必须通过setter provided by the ContainerAware class注入容器。

以下是通过DIC管理此类注射的方法,

your_service_id:
    class:  Path_to_your_service_class
    calls:
        - [setContainer, ['@service_container']]

<强> BUT,

由于您只是定位到实体管理器,您不需要来使您的类容器感知。只有当您的服务依赖于一组其他服务时才会注入容器(这里不是这种情况)

那么,请考虑仅注入doctrine.orm.entity_manager服务。 Check this relevant Example.