How to use factory encoder in symfony 2 inside model setup device?

This question is about Symfony 2.1

How can I encode a 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 the basic configuration:

# 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 password encryption process should follow the model. How can I use a standard factory encoder inside a model?

+5
source share
2 answers

The object contains data, but does not process it. If you want to modify object data, you can create an event listener and make the material persistent. Check How to register listeners and subscribers of events from official documentation.

FosUserBundle .

FosUserBundle UserManager

, , .

+3

@Vadim, - , prePersist, , persist flush setPassword. A getPassword , , . .

, " " , :

class UserManager
{
    // ...
    public function __construct(EncoderFactoryInterface $encoderFactory)
    {
        // $encoderFactory is injected by the DIC as requested by your service configuration
        // ...
    }

    public function setUserPassword(UserInterface $user, $plaintextPassword)
    {
        $hash = $this->encoderFactory->getEncoder($user)->encodePassword($plaintextPassword, null);
        $user->setPassword($hash);
    }
    // ...
}

, :

public function userRegistrationAction()
{
    // ... 
    if ($form->isValid()) {
        $user = new User();
        // ...
        $this->get('my.bundle.user_manager')->setUserPassword($user, $form->get('password')->getData());
        // ...
    }
}
+10

All Articles