如果你需要在symfony 2或3的自定义控制器中手动注册用户(无表单), 则只需访问控制器中的fos_user.user_manager服务即可。
你将要问自己, 为什么不简单地直接使用doctrine保留用户实体?答案很简单, 我们不想自己处理已经在FOSUserBundle中实现的加密内容。这就是为什么我们需要使用setPlainPassword方法访问服务。
注意:如果你不是从控制器手动实现用户插入, 则需要注入容器以便从任何位置检索fos_user服务。
class MyCustomuserController extends Controller
{
public function registeruserAction(Request $request){
$succesfullyRegistered = $this->register("demo@email.com", "demoUsername", "demoPassword");
if($succesfullyRegistered){
// the user is now registered !
}else{
// the user exists already !
}
}
/**
* This method registers an user in the database manually.
*
* @return boolean User registered / not registered
**/
private function register($email, $username, $password){
$userManager = $this->get('fos_user.user_manager');
// Or you can use the doctrine entity manager if you want instead the fosuser manager
// to find
//$em = $this->getDoctrine()->getManager();
//$usersRepository = $em->getRepository("mybundleuserBundle:User");
// or use directly the namespace and the name of the class
// $usersRepository = $em->getRepository("mybundle\userBundle\Entity\User");
//$email_exist = $usersRepository->findOneBy(array('email' => $email));
$email_exist = $userManager->findUserByEmail($email);
// Check if the user exists to prevent Integrity constraint violation error in the insertion
if($email_exist){
return false;
}
$user = $userManager->createUser();
$user->setUsername($username);
$user->setEmail($email);
$user->setEmailCanonical($email);
$user->setLocked(0); // don't lock the user
$user->setEnabled(1); // enable the user or enable it later with a confirmation token in the email
// this method will encrypt the password with the default settings :)
$user->setPlainPassword($password);
$userManager->updateUser($user);
return true;
}
}
评论前必须登录!
注册