Reputation: 194
In my repository, I would like to do something like:
public function generatePassword(Users $user, UserPasswordEncoderInterface $passwordEncoder)
{
return $passwordEncoder->encodePassword($user,$user->getPlainPassword());
}
but the function inside a controller expects the second argument. Is there a way to load UserPasswordEncoderInterface automatically or initialize it?
Upvotes: 0
Views: 95
Reputation: 169
You can do this by using constructor injection.
You should load your UserPasswordEncoderInterface
in your repository class and save it globally (in your class). You can use it then without having to declare it in a function parameter.
Something like this:
class Repository
{
private $passwordEncoder;
public function __construct(UserPasswordEncoderInterface $passwordEncoder)
{
$this->passwordEncoder = $passwordEncoder;
}
public function generatePassword(Users $user)
{
return $this->passwordEncoder->encodePassword($user,$user->getPlainPassword());
}
}
Also type-hint your service.
Upvotes: 2