我不希望用户能够选择他们的组,而是由系统内部管理。对于注册,使用 FOS 的工作并不多。我所需要的只是用一组新的学说键约束覆盖用户实体。我在扩展 BaseUser 的 User 实体中添加了以下内容:
/**
* User.
*
* @ORM\Table(name="fos_user",
* uniqueConstraints={
* @UniqueConstraint(name="group_username_unique", columns={"group_id", "username_canonical"}),
* @UniqueConstraint(name="group_email_unique", columns={"group_id", "email_canonical"})
* }
* )
* @UniqueEntity(fields={"group", "usernameCanonical"}, errorPath="username", message="fos_user.username.already_used")
* @UniqueEntity(fields={"group", "emailCanonical"}, errorPath="email", message="fos_user.email.already_used")
* @ORM\Entity
* @ORM\AttributeOverrides({
* @ORM\AttributeOverride(name="emailCanonical", column=@ORM\Column(type="string", length=180, nullable=false, unique=false)),
* @ORM\AttributeOverride(name="usernameCanonical",column=@ORM\Column(type="string", length=180, nullable=false, unique=false))
* })
*/
class User extends BaseUser
{
/* my entity contents here */
}
登录时,工作量有点大。我必须重写 UserProvider、UserManager、创建 CustomUserManager 并添加一组具有组约束的新方法:
public function findUserByUsernameOrEmailAndGroup($usernameOrEmail, $group)
{
if (preg_match('/^.+\@\S+\.\S+$/', $usernameOrEmail)) {
return $this->findUserByEmailAndGroup($usernameOrEmail, $group);
}
return $this->findUserByUsernameAndGroup($usernameOrEmail, $group);
}
public function findUserByEmailAndGroup($email, $group)
{
return $this->findUserBy(['group' => $group, 'emailCanonical' => $email]);
}
public function findUserByUsernameAndGroup($username, $group)
{
return $this->findUserBy(['group' => $group, 'usernameCanonical' => $username]);
}
public function findUserByConfirmationTokenAndGroup($token, $group)
{
return $this->findUserBy(['confirmationToken' => $token, 'group' => $group]);
}
此外,我对 RegistrationController 和 ResettingController 进行了覆盖,以适应登录和密码重置功能的新更改。