如何在 Symfony 中对任意实体的密码进行编码?

How to encode the password for an arbitrary entity in Symfony?

我正在 mysql 创建组织 table。

实体名为 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'
            );
        }

这是我得到的错误:

Cannot autowire argument $encoder of "App\Controller\OrganisationController::register()": it references interface "Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface" but no such service exists. Did you create a class that implements this interface?`

PasswordEncoderInterface不存在。

最简单的解决方案是让您的 Organisation class 实施 UserInterface.

UserPasswordEncoder 不期望 User 对象,而是实现该接口的对象。即使您的组织 class 本身不是 "user",看起来您希望它具有相同的界面(用户名、密码...)。

只需更改您的组织 class 以实现该接口,然后像往常一样注入 UserPasswordEncoderInterface

如果@yivi 的提议不适用于您的实体class,您可以手动将相应的编码器实现注入到您的控制器中。要么访问控制器中的容器,要么更好 configure your controllers as services and inject the service via setter injection.