yii2框架實現(xiàn)注冊:
在advanced模板中,進入frontend/index.php?r=site%2Fsignup頁面,可以看到框架的注冊頁面
填寫完Username、Email和Password后點擊Signup后,如果格式不對,frontend/models/SignuForm中的rules()函數(shù)會進行初步驗證,所有格式正確后,數(shù)據(jù)傳輸?shù)?frontend/controllers /SiteController中的 actionSignup()函數(shù)中,函數(shù)加載用戶輸入的注冊信息,在frontend/models/SignupForm中的signup()函數(shù)。
以下引用的文字為解釋函數(shù)中的具體細節(jié),不閱讀不影響整體,因為沒有折疊文字功能,故采用引用的方法,下同
if (!$this->validate()) { return null; }
signup() 函數(shù)首先調(diào)用 yii2/base/Model中的validate() 函數(shù)進行驗證
第一步,清除使用frontend/models/SignuForm中的rules()函數(shù)在用戶輸入時的錯誤信息
if ($clearErrors) { $this->clearErrors(); }
第二步,beforeValidate()函數(shù)觸發(fā)beforeValidate事件并返回true
第三步,設置scenario,默認是default
第四步,因為這里的$attributeNames為null,
$attributeNames = $this->activeAttributes();
執(zhí)行后返回
array(3) { [0]=> string(8) "username" [1]=> string(5) "email" [2]=> string(8) >"password" }
第五步,$this->getActiveValidators()會得到frontend/models/SignuForm中的rules()中11條驗證規(guī)則給validateAttributes()進行驗證
第六步,執(zhí)行afterValidate()函數(shù)觸發(fā)afterValidate事件
最后 如果所有驗證都通過,$this->hasErrors()為false,所以函數(shù)最后返回true
推薦學習:Yii入門教程