在PHP中,我们可以在UserService类中实现用户注册功能,如下所示:
<?php namespace App\Service; use AppEntity\User; use Propel\Runtime\Exception\PropelException; class UserService { public function registerUser($username, $password) { // 检查用户名是否已存在 $user = UserQuery::create()->findOneByUsername($username); if ($user !== null) { throw new PropelException("用户名已存在"); } // 创建新用户 $user = new User(); $user->setUsername($username); $user->setPassword(password_hash($password, PASSWORD_DEFAULT)); try { $user->save(); } catch (PropelException $e) { throw new PropelException("保存用户失败", 0, $e); } return $user; } }
在Java中,我们可以在UserService类中实现用户注册功能,如下所示:
package com.example.app.service; import com.example.app.entity.User; import com.example.app.exception.PropelException; import com.example.app.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired private UserRepository userRepository; public User registerUser(String username, String password) throws PropelException { // 检查用户名是否已存在 User user = userRepository.findByUsername(username); if (user != null) { throw new PropelException("用户名已存在"); } // 创建新用户并设置密码(使用bcrypt加密) user = new User(); user.setUsername(username); user.setPassword(passwordEncoder().encode(password)); // 假设已经导入了BCryptPasswordEncoder类和相应的包 try { userRepository.save(user); } catch (Exception e) { throw new PropelException("保存用户失败", e); } return user; } }
还没有评论,来说两句吧...