Kohana 3.2验证类的问题.当有错误时,它似乎没有发送异常


Problem with Kohana 3.2 Validation class. It seems it is not sending Exception when there is an error

当POST数据发送到:

Auth::instance()->register( $_POST );

然后验证数据…如果不是,我假设Kohana中的验证类会抛出异常。然后try-catch函数捕获它。我遇到的问题是使用这个方法:

$this->send_confirmation_email($_POST);

即使数据无效也会调用。我相信,如果数据是无效的,它会跳过其他一切,跳去捕捉……但似乎我错了,因为我从发送电子邮件的方法中得到了一个令人讨厌的致命错误,因为它找不到电子邮件地址…

try {
        if( ! $optional_checks ) {
           //throw new ORM_Validation_Exception("Invalid option checks");
        }
        $_POST['email_code'] = Auth::instance()->hash(date('YmdHis', time()));
        Auth::instance()->register( $_POST );
        $this->send_confirmation_email($_POST);
        // sign the user in
        Auth::instance()->login($_POST['username'], $_POST['password']);
        // redirect to the user account
        $this->request->redirect('user/profile');
     } catch (Validation_Exception $e) {

那么,是否有一种方法可以使发送电子邮件的方法跳过如果数据无效?

可以说我应该使用check()方法。这是一个问题的原因:

 Validation::factory($fields)
                    ->rules('username', $this->_rules['username'])
                    ->rule('username', 'username_available', array($this, ':field'))
                    ->rules('email', $this->_rules['email'])
                    ->rule('email', 'email_available', array($this, ':field'))
                    ->rules('password', $this->_rules['password'])
                    ->rules('password_confirm', $this->_rules['password_confirm']);
            if (Kohana::config('useradmin')->activation_code) {
                    Validation::factory($fields)->rule('activation_code', 'check_activation_code', array($this, ':field'));
            }

提前感谢您的帮助。

更新:

现在看来Kohana验证类有一个问题。

下面是Model_User类中的方法:

public function create_user($fields)
{
    Validation::factory($fields)
        ->rules('username', $this->_rules['username'])
        ->rule('username', 'username_available', array($this, ':field'))
        ->rules('email', $this->_rules['email'])
        ->rule('email', 'email_available', array($this, ':field'))
        ->rules('password', $this->_rules['password'])
        ->rules('password_confirm', $this->_rules['password_confirm']);
        //->labels($_labels);
    if (Kohana::config('useradmin')->activation_code) {
        Validation::factory($fields)->rule('activation_code', 'check_activation_code', array($this, ':field'));
    }
    // Generate a unique ID
    $uuid = CASSANDRA::Util()->uuid1();
    //CASSANDRA::selectColumnFamily('UsersRoles')->insert($username, array('rolename' => 'login'));
    CASSANDRA::selectColumnFamily('Users')->insert($uuid, array(
                            'username'      => $fields['username'],
                            'email'         => $fields['email'],
                            'password'      => Auth::instance()->hash($fields['password']),
                            'logins'        => 0,
                            'last_login'        => 0,
                            'last_failed_login' => 0,
                            'failed_login_count'    => 0,
                            'created'       => date('YmdHis', time()),
                            'modify'        => 0,
                            'role'          => 'login',
                            'email_verified'    => $fields['email_code'],
                        ));
}

验证类之后的代码被执行。因此,即使数据无效,它仍然会向数据库添加一个新用户。

我正在做的测试是空输入。

规则如下:

protected $_rules = array(
    'username' => array(
        'not_empty' => NULL,
        'min_length' => array(4),
        'max_length' => array(32),
        'regex' => array('/^[-'pL'pN_.]++$/uD'),    
    ),
    'password' => array(
        'not_empty' => NULL,
        'min_length' => array(8),
        'max_length' => array(42),
    ),
    'password_confirm' => array(
        'matches' => array('password'),
    ),
    'email' => array(
        'not_empty' => NULL,
        'min_length' => array(4),
        'max_length' => array(127),
        'validate::email' => NULL,
    ),
);

再次感谢您的帮助。

设置规则的方式是错误的,我设置Validation自定义规则的方式也是错误的。下面是解决这个问题的代码:

protected $_rules = array(
    'username' => array(
        array('not_empty'),
        array('min_length', array(4)),
        array('max_length', array(32)),
        array('regex', array('/^[-'pL'pN_.]++$/uD')),
    ),
    'password' => array(
        array('not_empty'),
        array('min_length', array(8)),
        array('max_length', array(42)),
    ),
    'password_confirm' => array(
        array('matches', array(':validation', ':field', 'password')),
    ),
    'email' => array(
        array('not_empty'),
        array('min_length', array(4)),
        array('max_length', array(127)),
        array('email'),
    ),
);
验证:

$validation = Validation::factory($fields)
        ->rules('username', $this->_rules['username'])
        ->rule('username', array($this, 'username_available'), array(':validation', ':field'))
        ->rules('email', $this->_rules['email'])
        ->rule('email', array($this, 'email_available'), array(':validation', ':field'))
        ->rules('password', $this->_rules['password'])
        ->rules('password_confirm', $this->_rules['password_confirm'])
        ->errors('register/user');
        //->labels($_labels);
    if (Kohana::config('useradmin')->activation_code) {
        $validation->rule('activation_code', array($this, 'check_activation_code'), array(':validation', ':field'));
    }
    if(!$validation->check())
    {
        throw new Validation_Exception($validation, __('Your registering information is not valid.'));
    }

感谢大家的支持!

有一个叫做if-else的东西你可以用…;)

你关于try-catch如何工作的想法是正确的:当在try块中抛出异常时,其中所有剩余的代码将被跳过,并直接跳转到catch块中。

很可能register函数只是没有像您假设的那样抛出异常,这将是您的代码没有做您认为应该做的事情的原因。

在这种情况下,Kohana Auth类没有默认的register()方法。

我已经实现了这个方法使用在一个特定的情况下,与AmfPHP网关Kohana Useradmin模块。

正确的方法是使用model方法来添加user和它的角色,如果包含字段的数组无效,你将得到一个抛出。

您可以从Auth->instance()->register()中得到如下结果:

    if(! Auth::instance()->register( $_POST )) throw new Validation_Exception(...);

尝试或最好的方法是将Auth->instance()->register($_POST)更改为:

    $user->create_user($_POST, array(
        'username',
        'password',
        'email',
    ));
    // Add the login role to the user (add a row to the db)
    $login_role = new Model_Role(array('name' =>'login'));
    $user->add('roles', $login_role);

它将使您的try catch工作所需的Kohana_Validation异常。

最后,这里是来自寄存器方法的代码,它可以帮助你:

/**
 * Register a single user
 * Method to register new user by Useradmin Auth module, when you set the
 * fields, be sure they must respect the driver rules
 * 
 * @param array $fields An array witch contains the fields to be populate
 * @returnboolean Operation final status
 * @see Useradmin_Driver_iAuth::register()
 */
public function register($fields) 
{
    if( ! is_object($fields) ) 
    {
        // Load the user
        $user = ORM::factory('user');
    } 
    else 
    {
        // Check for instanced model
        if( $fields instanceof Model_User ) 
        {
            $user = $fields;
        } 
        else 
        { 
            throw new Kohana_Exception('Invalid user fields.');
        }
    }
    try 
    {
        $user->create_user($fields, array(
            'username',
            'password',
            'email',
        ));
        // Add the login role to the user (add a row to the db)
        $login_role = new Model_Role(array('name' =>'login'));
        $user->add('roles', $login_role);
    } 
    catch (ORM_Validation_Exception $e) 
    {
        throw $e;
        return FALSE;
    }
    return TRUE;
}