而无需使用Kohana再次定义它们

而无需使用Kohana再次定义它们

本文介绍了有没有一种方法可以覆盖模型属性,而无需使用Kohana再次定义它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有以下内容:

class Model_User extends ORM {
    protected $_rules = array(
        'username' => array(
            'not_empty'  => NULL,
            'min_length' => array(6),
            'max_length' => array(250),
            'regex'      => array('/^[-\pL\pN_@.]++$/uD'),
        ),
        'password' => array(
            'not_empty'  => NULL,
            'min_length' => array(5),
            'max_length' => array(30),
        ),
        'password_confirm' => array(
            'matches'    => array('password'),
        ),
    );
}

class Model_UserAdmin extends Model_User {
    protected $_rules = array(
        'username' => array(
            'not_empty'  => NULL,
            'min_length' => array(6),
            'max_length' => array(250),
            'regex'      => array('/^[-\pL\pN_@.]++$/uD'),
        ),
        'password' => array(
            'not_empty'  => NULL,
            'min_length' => array(5),
            'max_length' => array(42),
        ),
    );
}

在这里,Model_UserAdmin扩展了Model_User并覆盖了密码的最大长度,并删除了对password_confirm的验证(这不是实际情况,而是示例).

In here, Model_UserAdmin extends Model_User and overrides the max length for password and removes the validation for password_confirm (this is not an actual case, but an example).

有没有比重新定义整个$_rules属性/数组更好的方法了?

Is there a better way instead of redefining the entire $_rules property/array?

推荐答案

如果要在会话中存储UserAdmin模型(如Auth模块一样),请使用_initialize()而不是__construct($id).序列化的ORM对象不会调用__construct(),因此部分规则将丢失. _initialize()方法为模型属性(例如table_name,关系等)设置默认值

Use _initialize() instead of __construct($id) if you want to store your UserAdmin model in session (like Auth module does). Serialized ORM objects will not call __construct(), so part of your rules will lost. _initialize() method sets default values for model properties like table_name, relationships etc

protected function _initialize()
{
   // redefine model rules
   $this->_rules['password']['max_length'] = 42 ;
   unset($this->_rules['password_confirm']) ;
   // call parent method
   parent::_initialize();
}

这篇关于有没有一种方法可以覆盖模型属性,而无需使用Kohana再次定义它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 07:28