【问题标题】:How to encode the password for an arbitrary entity in Symfony?如何在 Symfony 中为任意实体编码密码?
【发布时间】:2020-03-02 21:10:45
【问题描述】:

我正在 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”,但不存在这样的服务。您是否创建了实现此接口的类?`

【问题讨论】:

    标签: php symfony symfony4 symfony-security


    【解决方案1】:

    PasswordEncoderInterface 不存在。

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

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

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

    【讨论】:

      【解决方案2】:

      如果@yivi 的提议不适用于您的实体类,您可以手动将相应的编码器实现注入您的控制器。要么访问控制器中的容器,要么更好地使用configure your controllers as services 并通过setter injection 注入服务。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-10-06
        • 1970-01-01
        • 1970-01-01
        • 2022-06-10
        • 1970-01-01
        • 2021-03-01
        相关资源
        最近更新 更多