註冊時,我想檢查另一個表,如果他們的用戶名存在,並且如果有,請爲該用戶設置另一個角色。Symfony FOSUserbundle - 創建帳戶角色的最佳實踐(使用db查詢)
我會在用戶事件構造函數,監聽器,註冊控制器中執行此操作嗎?我嘗試了這些,但有問題的實際訪問實體管理器來查詢表
那麼我現在想運行(的地方),當用戶正在註冊(或確認他們的電子郵件)
$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 IM補充(9.3)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);
}
我可能會做它在登記控制器(除非有是用戶可以註冊的其他地方嗎?)。你對EntityManager有什麼樣的麻煩? – Rhono
就像這個例子? http://symfony.com/doc/current/bundles/FOSUserBundle/overriding_controllers.html – p3tch