dektrium/yii2-user RegistrationForm.php different array definition on rules()

Hi there everybody!

Some days ago I had to override the RegistrationForm.php from dektrium/yii2-user module and I have noticed as the array returned from the rules() method is an associative one having, as key, a sort of description of the particular rule:




 /**

     * @inheritdoc

     */

    public function rules()

    {

        $user = $this->module->modelMap['User'];

        return [

            // username rules

            'usernameLength'   => ['username', 'string', 'min' => 3, 'max' => 255],

            'usernameTrim'     => ['username', 'filter', 'filter' => 'trim'],

            'usernamePattern'  => ['username', 'match', 'pattern' => $user::$usernameRegexp],

            'usernameRequired' => ['username', 'required'],

            'usernameUnique'   => [

                'username',

                'unique',

                'targetClass' => $user,

                'message' => Yii::t('user', 'This username has already been taken')

            ],

            // email rules

            'emailTrim'     => ['email', 'filter', 'filter' => 'trim'],

            'emailRequired' => ['email', 'required'],

            'emailPattern'  => ['email', 'email'],

            'emailUnique'   => [

                'email',

                'unique',

                'targetClass' => $user,

                'message' => Yii::t('user', 'This email address has already been taken')

            ],

            // password rules

            'passwordRequired' => ['password', 'required', 'skipOnEmpty' => $this->module->enableGeneratingPassword],

            'passwordLength'   => ['password', 'string', 'min' => 6, 'max' => 72],

        ];

    }




Whereas in all the other rules() definition I have found so far (as well as those generated with gii module) the returned array do not have any key but just the single rules, like this one:




/**

     * @inheritdoc

     */

    public function rules()

    {

        return [

            [['name', 'email', 'subject', 'body'], 'required'],

            ['email', 'email'],

            ['verifyCode', 'captcha'],

        ];

    }



My question is: is there a particular reason for using associative arrays in place of normal ones? It might be useful for something?

Thanks and Cheers

;D

I think I might get why of this particular design: If you will need to extend the class and modify a single rule you just have to override the rules() method, get the array from the parent method




$rules = parent::rules();



and modify the single rule by getting it given its key. For example to modify the password minimum length you can do like this:




$rules['passwordLength']['min'] = 8;



Putting all together:




/**

* @inheritdoc

*/

public function rules(){

   $rules = parent::rules();

   $rules['passwordLength']['min'] = 8;

   return $rules;

}



That’s cool, isn’t it? ;)