在和ucenter通信成功后,实现注册登录就非常简单了。简要记录如下。
1 新建一个controller用来继承Ucenter\Controller\UcController,并新建构造方法,用来实例化UcController
init();
}
}
2 index controller添加uc类变量。private $uc;
3 index方法中实例化uc控制器,对UCenter接口的操作通过$this->uc来完成。$this->uc = new uc();
以上两步完成后,就可以在代码合适的地方调用ucenter接口进行注册登录了。以下是我项目中的代码片段,仅供参考。
4 注册时验证用户名是否已经存在以及是否合法
$username = $data['Content'];
$result = $this->uc->uc_check_name($username);
switch ($result) {
case -1:
$reason = "用户名不合法";
break;
case -2:
$reason = "包含不允许注册的词语";
break;
case -3:
$reason = "用户名已经存在";
break;
}
if ($result != 1) {
$this->_resetStep();
return array(join("\n", array_merge(array('【注册】注册失败', $reason), $this->_guestActions()
)),
'text');
} else {
$this->_setStep(self::STEP_REGISTER_PASSWORD);
Session::set('username', $data['Content']);
return array('【注册】请输入密码', 'text');
}
}
5 输入密码后调用ucenter进行注册,因为ucenter注册时必带username,password,email,所以需要为用户生成默认的email
//注册->输入密码
if ($this->_currentStep() == self::STEP_REGISTER_PASSWORD) {
$this->_resetStep();
Session::set('password', $data['Content']);
//call ucenter to register user
$username_valid = $this->uc->uc_check_name(Session::get('username'));
Log::write('$username_valid' . $username_valid, 'debug');
if ($username_valid == 1) {
//register
Log::write('start register ' . Session::get('username'), 'debug');
$email = "reg_" . substr(Session::getId(), 0, 3) . time() . substr(Session::getId(), 7, 4) .
"@null.null";
//$email = Session::get('username').'@'.Session::get('username').'.com';
$register_result = $this->uc->uc_register(Session::get('username'), Session::get('password'),
$email);
Log::write('register result is ' . $register_result, 'debug');
switch ($register_result) {
case -1:
$reason = "用户名不合法";
break;
case -2:
$reason = "包含不允许注册的词语";
break;
case -3:
$reason = "用户名已经存在";
break;
case -4:
$reason = "Email格式有误";
break;
case -5:
$reason = "Email不允许注册";
break;
case -6:
$reason = "该Email已经被注册";
break;
}
if ($register_result > 0) {
Log::write('Ucenter register successful' . Session::get('username'), 'debug');
return array(join("\n", array_merge(array('【注册】注册成功'), $this->_guestActions())), 'text');
} else {
Log::write('Ucenter register failed' . $reason, 'debug');
$this->_resetSession();
return array(join("\n", array_merge(array('【注册】注册失败', $reason), $this->_guestActions()
)),
'text');
}
}
}
6 登录时传入用户输入的用户名和密码即可。登陆成功后将用户名和密码写入session文件。
$result = $this->uc->uc_login(Session::get('username'), $data['Content']);