如何在Symfony中为任意实体编码密码



我正在mysql中创建组织表。

该实体称为Organisation,它有一个password字段。

当我尝试使用UserPasswordEncoderInterface时,它需要user实体,所以这不起作用。我尝试使用PasswordEncoderInterface,但它表示该服务不存在。这里能做什么?

这是我的代码:

public function register(Request $request, EntityManagerInterface $entityManager, PasswordEncoderInterface $encoder)
{
$organisation = new Organisation();
$form = $this->createForm(OrganisationRegisterType::class, $organisation);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$plainPassword = $form->getData()->getPassword();
$encoded = $encoder->encodePassword($plainPassword, null);
$organisation->setPassword($encoded);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($organisation);
$entityManager->flush();
$this->addFlash(
'success',
'Organizacija sukurta sėkmingai. Nurodytu el. paštu buvo išsiųsta prisijungimo informacija'
);
}

这是我得到的错误:

无法自动连接"App\Controller\OrganisationController::register(("的参数$encoder:它引用接口"Symfony\Component\Security\Core\encoder\PasswordEncoderInterface",但不存在此类服务。您是否创建了实现此接口的类?`

PasswordEncoderInterface不存在。

最简单的解决方案是让Organisation类实现UserInterface

UserPasswordEncoder不需要User对象,而是需要实现该接口的对象。即使你的组织类本身不是一个"用户",看起来你希望它有相同的界面(用户名、密码…(

只需更改组织类以实现该接口,并像往常一样注入UserPasswordEncoderInterface即可。

如果@yivi的提议不适用于实体类,则可以手动将相应的编码器实现注入控制器。访问控制器中的容器,或者更好地将控制器配置为服务,并通过setter注入注入服务。

最新更新