gpt4 book ai didi

php - 基于异常的表单验证

转载 作者:搜寻专家 更新时间:2023-10-31 22:13:02 26 4
gpt4 key购买 nike

我使用哨兵作为我的应用程序的授权包,这是我注册用户的 Controller 方法。

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);
}

}

如您所见,我混淆了验证错误和异常,我想知道是否有一种方法可以使用异常来处理所有错误?

最佳答案

我建议创建一个私有(private)方法,该方法在出错时抛出 Exception 以使其同构。

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

然后在你的try block 上调用它

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
}
//...
}

关于php - 基于异常的表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10409154/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com