frontend\models\SignupMobileVerifyForm::signup PHP Method

signup() public method

Signs user up.
public signup ( $runValidation = true ) : User | false
return common\models\User | false the saved model or false if saving fails
    public function signup($runValidation = true)
    {
        if ($runValidation && !$this->validate()) {
            return false;
        }
        $user = new User();
        $user->mobile = $this->_session['mobileSignup'];
        $user->setPassword($this->_session['mobileSignupPassword']);
        $user->generateAuthKey();
        $user->generateAccessToken();
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$user->save(false)) {
                throw new \Exception();
            }
            $userAccount = new UserAccount();
            $userAccount->id = $user->id;
            $userAccount->password_hash = null;
            if (!$userAccount->save(false)) {
                throw new \Exception();
            }
            $transaction->commit();
            return $user;
        } catch (\Exception $e) {
            $transaction->rollBack();
            return false;
        }
    }

Usage Example

 public function actionSignup($step = '1')
 {
     if ($step === '1') {
         $model = new SignupForm();
         if ($model->load(Yii::$app->request->post(), '') && $model->validate()) {
             $model->writeSession();
             if ($sent = $this->_sendMsg($model->mobile)) {
                 Yii::info("用户注册发送短信验证码成功!手机号:{$model->mobile}");
             } else {
                 Yii::warning("用户注册发送短信验证码失败!手机号:{$model->mobile},说明:" . Yii::$app->smser->message);
             }
             return ['status' => 'success', 'data' => ['isSent' => $sent]];
         } else {
             return ['status' => 'fail', 'data' => ['errors' => $model->getFirstErrors()]];
         }
     } elseif ($step === '2') {
         $session = Yii::$app->session;
         $session->open();
         if (empty($session['mobileSignup']) || empty($session['mobileSignupTimeout']) || $session['mobileSignupTimeout'] < time()) {
             return ['status' => 'fail', 'data' => ['errors' => ['对不起,请您重新注册。']]];
         }
         $model = new SignupMobileVerifyForm();
         if ($model->load(Yii::$app->request->post(), '') && $model->validate()) {
             if ($user = $model->signup()) {
                 $model->clearSession();
                 return ['status' => 'success', 'data' => ['accessToken' => $user->access_token]];
             }
         }
         return ['status' => 'fail', 'data' => ['errors' => $model->getErrors('verifyCode') ?: ['注册失败,请稍后再试。']]];
     } else {
         throw new BadRequestHttpException('参数错误!');
     }
 }