Search code examples
phpsymfony-2.6

Symfony2 dyn. password encoding


I'm trying to get an own UserBundle to work on sf 2.6.3, using the following guide: Symfony Book.

I've pasted that example code in my setPassword method within the user entity (no idea if thats how it's meant to use, though), changing it to fit (see code below).

It comes out, that I get an error 'field container not found in class [...]' and 'method encodePassword not found in class [...]', but the description is missing which Container to use...

//MyProject\UserBundle\Entity\User.php
namespace MyProject\UserBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\User\UserInterface;

//...

public function setPassword($password)
{
    $encoder = $this->container->get('security.password_encoder');
    $encoded = $encoder->encodePassword($this, $password);

    $this->password = $encoded;

    return $this;
}

//...

Do I only miss a use-statement, or is it more complex? I was looking up several links, but found several use-statements which use a container-thing, so I've no clue which is the right one... Any suggestions?

Thanks in advance ;)


Solution

  • You need to define a method encodePassword because this IS NOT a native SYmfony2 method. For example,

    private function encodePassword(User $user, $plainPassword)
    {
        $encoder = $this->container->get('security.encoder_factory')
            ->getEncoder($user)
        ;
    
        return $encoder->encodePassword($plainPassword, $user->getSalt());
    }