2012-05-02 44 views
3

我使用sentry作爲我的應用程序的auth包,這是我用於註冊用戶的控制器方法。基於異常的表單驗證

class Controller_Auth extends \Controller_Base 
{ 

    function action_signup($type='user') 
    { 
     $user = \Fieldset::forge('new_user'); 
     $user->add('email', 'Email', array(), array(array('required'), array('valid_email'))); 
     $user->add('password', 'Password', array(), array(array('required'))); 
     $user->add('confirm_password', 'Confirm Password', array(), array(array('match_field', 'password'))); 
     $user->add('submit', '', array('value'=>'Sign Up', 'class' => 'btn', 'type'=>'submit')); 

     $user->repopulate(); 

     if($user->validation()->run()) 
     { 

      try 
      { 
       $fields = $user->validated(); 

       $user_id = \Sentry::user()->create(array('email'=>$fields['email'], 'password'=>$fields['password'])); 

       if($user_id) 
       { 
        // the user was created - send email notifying user account was created 
       } 
       else 
       { 
        // something went wrong - shouldn't really happen 
       } 
      } 
      catch(\SentryUserException $e) 
      { 
       \Library_Message::set('error', $e->getMessage()); 
      } 
      catch(\Database_Exception $e) 
      { 
       \Library_Message::set('error', 'Database error occured. Please try again'); 
      } 
     } 
     else 
     { 
      \Library_Message::set('error', $user->validation()->errors()); 
     } 

     $this->template->set('content', $user->form(), false); 
    } 

} 

正如你可以看到我混淆了這兩個驗證錯誤和異常,我想知道如果有一種方法來處理使用異常的所有錯誤?

+9

這是不是特別有幫助的,但可以說你不應該使用異常來指示驗證失敗。例外情況應該用於您希望一切順利進行的「特殊」情況。驗證碼的性質預計會失敗。 –

回答

0

我建議創建一個私有方法,拋出一個異常的錯誤,以使其均勻。

/** 
* 
* @throws Exception 
*/ 
private function validateUserRun($user) { 
    if(!$user->validation()->run()) { 
     throw new YourException(); //Use a different exception than 'Exception' please 
    } 
} 

然後調用它的嘗試

function action_signup($type='user') { 
//... 
    try { 
    $this->validateUserRun($user); 
    $fields = $user->validated(); 
    //... 
    } 
    catch(\SentryUserException $e) { 
      \Library_Message::set('error', $e->getMessage()); 
    } catch(\Database_Exception $e) { 
      \Library_Message::set('error', 'Database error occured. Please try again'); 
    } catch (YourException $e) { 
     //Here you can catch the exception 
    } 
//... 
}