User Provider构造函数第二个参数

时间:2014-08-08 08:51:16

标签: symfony service doctrine-orm

我有一个简单的自定义UserProvider

class UserProvider extends EntityRepository implements UserProviderInterface
{
public function loadUserByUsername($username)
{
    $q = $this
        ->createQueryBuilder('u')
        ->where('u.username = :username OR u.email = :email')
        ->setParameter('username', $username)
        ->setParameter('email', $username)
        ->getQuery();

    try {
        $user = $q->getSingleResult();
    } catch (NoResultException $e) {
        $message = sprintf(
            'Unable to find an active admin EntUserBundle:User object identified by "%s".',
            $username
        );
        throw new UsernameNotFoundException($message, 0, $e);
    }

    return $user;
}

public function refreshUser(UserInterface $user)
{
    $class = get_class($user);
    if (!$this->supportsClass($class)) {
        throw new UnsupportedUserException(
            sprintf(
                'Instances of "%s" are not supported.',
                $class
            )
        );
    }

    return $this->find($user->getId());
}

public function supportsClass($class)
{
    return $this->getEntityName() === $class
        || is_subclass_of($class, $this->getEntityName());
}
}

以及相应的服务

ent.user_provider:
    class: Ent\UserBundle\Entity\UserProvider
    arguments:
        em: "@doctrine"

我有这个错误

ContextErrorException: Catchable Fatal Error: Argument 2 passed to Doctrine\ORM\EntityRepository::__construct() must be an instance of Doctrine\ORM\Mapping\ClassMetadata, none given

我知道Symfony API它需要2个参数,第2个是Mapping \ ClassMetadata,但我应该在服务上作为参数提供什么?

提前致谢,

1 个答案:

答案 0 :(得分:0)

  1. UserProvider班级中创建构建:

    use Symfony\Component\Security\Core\User\UserProviderInterface;
    use Doctrine\ORM\EntityManager;
    ...
    
    class UserProvider implements UserProviderInterface
    {
        protected $em;
    
        public function __construct(EntityManager $em)
        {
           $this->em = $em;
        }
    
       public function loadUserByUsername($username)
       {
          $q = $this->em->getRepository('Acme\DemoBundle\Entity\User')->createQueryBuilder('u')
              ->where('u.username = :username OR u.email = :email')
              ->setParameter('username', $username)
              ->setParameter('email', $username)
              ->getQuery();
        ....
       }
       // other methods required by UserProviderInterface
    }
    
  2. 在services.yml中:

    ent.user_provider:
        class: Ent\UserBundle\Entity\UserProvider
        arguments: ["@doctrine.orm.default_entity_manager"]
    
  3. 这是用Symfony 2.5测试的。