注册时,我想检查另一个表是否存在用户名,如果存在,请为该用户设置另一个角色。
我会在用户事件构造函数,监听器,注册控制器中执行此操作吗?我尝试了其中几个,但实际上访问实体管理器以查询表
那么当用户注册(或确认他们的电子邮件)时,我想要(某处)运行
$em = $this->getDoctrine()->getEntityManager();
$uniID = preg_replace('/\D/', '', $user->getUsername());
if ($em->getRepository('AppBundle:User')->userHasMembership($uniID) == 1) {
$user->addRole('ROLE_MEMBER');
} else {
$user->removeRole('ROLE_MEMBER');
}
$em->persist($user);
$em->flush();
现在我已将实体经理注入我的服务
app.registration_completed:
class: UserBundle\EventListener\RegistrationConfirmListener
arguments:
- "@doctrine.orm.entity_manager"
我的事件监听器如下
类RegistrationConfirmListener实现EventSubscriberInterface {
protected $em;
function __construct(EntityManager $em)
{
$this->em = $em;
}
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::REGISTRATION_CONFIRM => 'onRegistrationConfirm'
);
}
public function onRegistrationConfirm(GetResponseUserEvent $event)
{
$user = $event->getUser();
$uniID = preg_replace('/\D/', '', $user->getUsername());
if ($this->em->getRepository('AppBundle:User')->userHasMembership($uniID) == 1) {
$roles = array('ROLE_USER', 'ROLE_MEMBER');
} else {
$roles = array('ROLE_USER');
}
$user->setRoles($roles);
}
答案 0 :(得分:0)
您发布了有问题的错误。我建议您始终与您尝试过的代码共享错误,以便其他人能够顺从解决问题。
请在下面尝试。
只需在服务中传递doctrine
对象参数,并在__construct()
中设置实体管理器。
<强> services.yml 强>
app.registration_completed:
class: UserBundle\EventListener\RegistrationConfirmListener
arguments:
- "@doctrine"
<强> RegistrationConfirmListener.php 强>
class RegistrationConfirmListener implements EventSubscriberInterface {
protected $em;
function __construct(Doctrine $doctrine) // Get doctrine argument
{
$this->em = $doctrine->getEntityManager();
}
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::REGISTRATION_CONFIRM => 'onRegistrationConfirm'
);
}
public function onRegistrationConfirm(GetResponseUserEvent $event)
{
$user = $event->getUser();
$uniID = preg_replace('/\D/', '', $user->getUsername());
if ($this->em->getRepository('AppBundle:User')->userHasMembership($uniID) == 1) {
$roles = array('ROLE_USER', 'ROLE_MEMBER');
} else {
$roles = array('ROLE_USER');
}
$user->setRoles($roles);
}
}
它在Symfony 2.3中运行良好