如何在Symfony 2中的模型设置器中使用编码器工厂? [英] How to use encoder factory in Symfony 2 inside the model setter?

查看:83
本文介绍了如何在Symfony 2中的模型设置器中使用编码器工厂?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于Symfony 2.1的问题

如何使用以下方式对用户密码进行编码:

$factory = $this->get('security.encoder_factory');
$user = new Acme\UserBundle\Entity\User();

$encoder = $factory->getEncoder($user);
$password = $encoder->encodePassword('ryanpass', $user->getSalt());
$user->setPassword($password);

和基本配置:

# app/config/security.yml
security:
    # ...

    encoders:
        Acme\UserBundle\Entity\User: sha512

在二传手模型内部:

class User implements UserInterface, \Serializable
{
    public function setPassword($password)
    {
       $this->password = $password;
    }
}

我认为加密密码的过程必须按型号进行. 我该如何在模型内使用Standart编码器工厂?

解决方案

该实体包含数据,但不处理数据.如果要更改实体的数据,则可以创建事件侦听器并在持久化之前执行操作.从官方文档中查看如何注册事件监听器和订阅者. >

您还可以查看 FosUserBundle 及其用户管理.

FosUserBundle UserManager

因此,主要思想是将纯格式的密码从表单传递给用户实体,并在使用事件监听器进行永久性编码之前对其进行编码.

This question about Symfony 2.1

How can I encode User password with:

$factory = $this->get('security.encoder_factory');
$user = new Acme\UserBundle\Entity\User();

$encoder = $factory->getEncoder($user);
$password = $encoder->encodePassword('ryanpass', $user->getSalt());
$user->setPassword($password);

And base config:

# app/config/security.yml
security:
    # ...

    encoders:
        Acme\UserBundle\Entity\User: sha512

Inside the setter models:

class User implements UserInterface, \Serializable
{
    public function setPassword($password)
    {
       $this->password = $password;
    }
}

I believe that the process of encryption password must deal by model. How can I use standart encoder factory inside the model?

解决方案

The entity contains data, not handles it. If you want to change data of an entity you can create the event listener and do stuff before persistence. Check How to Register Event Listeners and Subscribers from the official documentation.

You can also take a look at FosUserBundle and its user management.

FosUserBundle UserManager

So, the main idea is to pass plain password from a form to the user entity and encode it before persitence using event listener.

这篇关于如何在Symfony 2中的模型设置器中使用编码器工厂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆