【多人博客系统开发】用户注册模块

application/index/controller.User.php

assign("title","用户注册");
    return $this->fetch();
}

public function do_signup(Request $request){
    $validator = new Validator([         //new一个独立验证,定义验证规则 
        'captcha'=>'require|captcha',    //验证码
        'username'=>'require|alphaNum|max:40',
        'password'=>'require',
        ])
    if(!$validator->check($request->post())){
        $this->error($validator->getError());
    }
    try{
         $username = $request->post('username');
         $password = $request->post('password');
        if(!$this->service->signup($username,$password)){
            $this->error('注册失败');
        }

        $this->success("注册成功!",'signin');
    }   
     catch(Exception $e){
        this->error($e->getMessage());
    }
}

application/common/service/UserService.php

public function signup($username,$password)
{
    //检查账号是否存在
$user = User::get(['username'=>$username]);
if(!empty($user)){
  throw new Exception('用户名已存在');
}
$password = password_hash($password,PASSWORD_DEFAULT);
$user= new User();
$user->data(['username'=>$username,'password'=>$password]);
return $user->save();
}

你可能感兴趣的:(PHP,php)