注冊(cè)
在advanced模板中,進(jìn)入frontend/index.php?r=site%2Fsignup頁面,可以看到框架的注冊(cè)頁面
填寫完Username、Email和Password后點(diǎn)擊Signup后,如果格式不對(duì),frontend/models/SignuForm中的rules()函數(shù)會(huì)進(jìn)行初步驗(yàn)證,所有格式正確后,數(shù)據(jù)傳輸?shù)?frontend/controllers /SiteController中的 actionSignup()函數(shù)中,函數(shù)加載用戶輸入的注冊(cè)信息,在frontend/models/SignupForm中的signup()函數(shù),
以下引用的文字為解釋函數(shù)中的具體細(xì)節(jié),不閱讀不影響整體,因?yàn)闆]有折疊文字功能,故采用引用的方法,下同
if (!$this->validate()) { return null; }
signup() 函數(shù)首先調(diào)用 yii2/base/Model中的validate() 函數(shù)進(jìn)行驗(yàn)證
第一步,清除使用frontend/models/SignuForm中的rules()函數(shù)在用戶輸入時(shí)的錯(cuò)誤信息
if ($clearErrors) { $this->clearErrors(); }
第二步,beforeValidate()函數(shù)觸發(fā)beforeValidate事件并返回true
第三步,設(shè)置scenario,默認(rèn)是default
第四步,因?yàn)檫@里的$attributeNames為null,
$attributeNames = $this->activeAttributes();
執(zhí)行后返回
array(3) { [0]=> string(8) "username" [1]=> string(5) "email" [2]=> string(8) >"password" }
第五步,$this->getActiveValidators()會(huì)得到frontend/models/SignuForm中的rules()中11條驗(yàn)證規(guī)則給validateAttributes()進(jìn)行驗(yàn)證
第六步,執(zhí)行afterValidate()函數(shù)觸發(fā)afterValidate事件
最后 如果所有驗(yàn)證都通過,$this->hasErrors()為false,所以函數(shù)最后返回true
我們看一下數(shù)據(jù)表user的字段
用戶輸入了username、password和email,Yii2框架是如何生成其他的字段的呢,先看password_hash,在SignupFrom中的signup函數(shù)中的密碼生成是setPassword函數(shù),該函數(shù)在common/models/User中,setPassword函數(shù)調(diào)用了yii2/base/Security中的每一條規(guī)則generatePasswordHash函數(shù)。
if (function_exists('password_hash')) { /** @noinspection PhpUndefinedConstantInspection */ return password_hash($password, PASSWORD_DEFAULT, ['cost' => $cost]); }
如果有,就使用password_hash函數(shù)進(jìn)行加密,如果PHP沒有password_hash函數(shù),就使用crypt函數(shù)加密,初步判斷應(yīng)該是為了兼容PHP低于5.5的版本,畢竟大于5.5的版本才開始有password_hash函數(shù)
common/models/User的signup()函數(shù)在對(duì)password加密后,就會(huì)繼續(xù)生成一個(gè)auth key,auth key是當(dāng)用戶在登錄的時(shí)候點(diǎn)擊 remember me的時(shí)候的驗(yàn)證信息,
auth key生成的方法也是在yii2/base/Security中的generateRandomString,generateRandomString調(diào)用generateRandomKey函數(shù),如果你的PHP版本為是5.2~5.6或者是7,那就是用random_bytes生成一個(gè)32個(gè)字節(jié)的字符串,如果不是,當(dāng)你用的系統(tǒng)時(shí)windows并且安裝了OpenSSL,就會(huì)調(diào)用openssl_random_pseudo_bytes函數(shù)生成,如果你未安裝OpenSSL,就會(huì)使用mcrypt_create_iv生成。
如果你使用的系統(tǒng)不是windows,就需要調(diào)用/dev/urandom,FreeBSD系統(tǒng)特殊,會(huì)調(diào)用/dev/random,然后調(diào)用stream_set_read_buffer方法生成8字節(jié)的字符文件,生成后,通過fread函數(shù)讀取該文件中的32個(gè)字節(jié),然后返回該數(shù)據(jù)。
password_reset_token在用戶注冊(cè)的時(shí)候是為空的,當(dāng)用戶忘記密碼在登錄頁面點(diǎn)擊reset it 后生成的,用來給用法發(fā)送郵件后重置密碼時(shí)進(jìn)行驗(yàn)證。
status 在common/models/User中定義的
const STATUS_DELETED = 0; const STATUS_ACTIVE = 10;
用戶注冊(cè)時(shí)rules中的status默認(rèn)為為10,
created_time和updated_time也是在common/models/User中的behaviors()函數(shù)中生成
用戶的數(shù)據(jù)驗(yàn)證合格,加上框架生成的數(shù)據(jù),然后存儲(chǔ)進(jìn)數(shù)據(jù)的user表里。
推薦學(xué)習(xí):yii框架