2016-11-09 30 views
1

註冊時,我想檢查另一個表,如果他們的用戶名存在,並且如果有,請爲該用戶設置另一個角色。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); 
} 
+0

我可能會做它在登記控制器(除非有是用戶可以註冊的其他地方嗎?)。你對EntityManager有什麼樣的麻煩? – Rhono

+0

就像這個例子? http://symfony.com/doc/current/bundles/FOSUserBundle/overriding_controllers.html – p3tch

回答

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

+0

是的,它的作品,我想知道什麼是最好的做法是 – p3tch