简体   繁体   English

OctoberCMS如何覆盖用户插件的onRegister()函数?

[英]OctoberCMS How to Override Users Plugin onRegister() Function?

I'm using OctoberCMS based on Laravel. 我使用OctoberCMS基于Laravel。

I'm trying to override the Users Plugin onRegister() function. 我试图覆盖用户插件 onRegister()函数。

A previous answer helped me extend the plugin. 先前的答案帮助我扩展了插件。

I want to restrict Usernames to alphanumeric only with alpha_dash and limit to 50 characters. 我想仅使用alpha_dash将用户名限制为字母数字,并且限制为50个字符。

The original function in Account.php Account.php中的原始功能

public function onRegister()
{
...
    if ($this->loginAttribute() == UserSettings::LOGIN_USERNAME) {
        $rules['username'] = 'required|between:2,255';
    }

My Override 我的优先

Users Events docs https://github.com/rainlab/user-plugin#events 用户事件文档https://github.com/rainlab/user-plugin#events

public function boot() {

    \RainLab\User\Models\User::extend(function($model) {

        $model->bindEvent('model.beforeUpdate', function() use ($model) {

            # User Register
            \Event::listen('rainlab.user.register', function($user, $data) {

                if ($this->loginAttribute() == UserSettings::LOGIN_USERNAME) {
                    $rules['username'] = 'required|alpha_dash|between:2,50';
                }

            });
        }); 
    }); 
}

Error 错误

"Call to undefined method [loginAttribute]"

If I remove the if statement and loginAttribute and use only $rules['username'], I am still able to register names with non-alphanumeric characters. 如果删除if语句和loginAttribute并仅使用$ rules ['username'],则仍可以使用非字母数字字符注册名称。

I have been able to extend new code using this, but not override existing code. 我已经能够使用此扩展新代码,但不能覆盖现有代码。

I don't think you understand the page cycle here. 我认为您在这里不了解页面循环。

rainlab.user.register is called after the user has already been registered. 在用户已经注册之后,将调用rainlab.user.register Ie they have already passed validation and already exist with the invalid username. 也就是说,他们已经通过验证,并且已经使用无效的用户名存在。

What you can do instead is bind to the User model's model.beforeSave event and do your own validation of the username: 相反,您可以做的是绑定到User模型的model.beforeSave事件,并自己验证用户名:

public function boot() {

    \RainLab\User\Models\User::extend(function($model) {

        $model->bindEvent('model.beforeSave', function() use ($model) {
            $validator = \Validator::make($model->attributes, [
                'username' => 'required|alpha_dash|between:2,50',
            ]);

            if ($validator->fails()) {
                throw new \ValidationException([
                    'username' => 'Username must contain alphanumeric values only, and be between 2 and 50 characters in length',
                ]);
            }
        });

    });

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM