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

zlo*_*tte 1 php symfony symfony-security symfony4

我正在 mysql 中创建组织表。

\n\n

该实体被称为Organisation并且它有一个password字段。

\n\n

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

\n\n

这是我的代码:

\n\n
   public function register(Request $request, EntityManagerInterface $entityManager, PasswordEncoderInterface $encoder)\n    {\n        $organisation = new Organisation();\n\n        $form = $this->createForm(OrganisationRegisterType::class, $organisation);\n\n        $form->handleRequest($request);\n\n        if ($form->isSubmitted() && $form->isValid()) {\n            $plainPassword = $form->getData()->getPassword();\n            $encoded = $encoder->encodePassword($plainPassword, null);\n            $organisation->setPassword($encoded);\n\n            $entityManager = $this->getDoctrine()->getManager();\n            $entityManager->persist($organisation);\n            $entityManager->flush();\n\n            $this->addFlash(\n                \'success\',\n                \'Organizacija sukurta s\xc4\x97kmingai. Nurodytu el. pa\xc5\xa1tu buvo i\xc5\xa1si\xc5\xb3sta prisijungimo informacija\'\n            );\n        }\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是我得到的错误:

\n\n
\n

无法自动装配“App\\Controller\\OrganizationController::register()”的参数 $encoder:它引用接口“Symfony\\Component\\Security\\Core\\Encoder\\PasswordEncoderInterface”,但不存在此类服务。您是否创建了一个实现此接口的类?

\n
\n

yiv*_*ivi 5

PasswordEncoderInterface存在。

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

不需要UserPasswordEncoder一个User对象,而是一个实现该接口的对象。即使您的组织类本身不是“用户”,您似乎也希望它具有相同的界面(用户名、密码...)。

只需更改您的组织类来实现该接口,然后UserPasswordEncoderInterface照常注入即可。