Symfony 2.3。用户名或电子邮件登录

时间:2014-02-25 07:40:17

标签: php symfony symfony-2.3

我希望用户可以通过用户名或电子邮件登录。根据{{​​3}}我的security.yml代码是

providers:
     entity_members:
        entity: 
            class: AcmeBundle:Members

它给出错误

Doctrine存储库“Doctrine \ ORM \ EntityRepository”必须实现UserProviderInterface 如果通过

附加实体提供者
property: username

然后我只能通过用户名登录而不是电子邮件我的存储库类是

        namespace PropertyMart\UserBundle\Entity;

        use Symfony\Component\Security\Core\User\UserInterface;
        use Symfony\Component\Security\Core\User\UserProviderInterface;
        use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
        use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
        use Doctrine\ORM\EntityRepository;
        use Doctrine\ORM\NoResultException;

        class MembersRepository 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 {
                    // The Query::getSingleResult() method throws an exception
                    // if there is no record matching the criteria.
                    $user = $q->getSingleResult();
                } catch (NoResultException $e) {
                    throw new UsernameNotFoundException(sprintf('Unable to find an active admin UserBundle:User object identified by "%s".', $username), null, 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());
            }
        }

无法缩短问题..... security.yml没有属性:用户名在symfony工作2.1 *

1 个答案:

答案 0 :(得分:3)

您的'Members'Entity类必须实现UserInterface。

前:

use Symfony\Component\Security\Core\User\UserInterface;

class Members implements UserInterface
{
 //.......
}