I am using Doctrine 2 in Zend framework. What I want is to update a user password, without the user being logged in. Is this the right way to do it in entity class?
public function updatePassword($userId, $new_pass, $em){
$em->getConnection()->getConfiguration()->setSQLLogger( new \Doctrine\DBAL\Logging\EchoSQLLogger());
$qb = $em->createQueryBuilder();
$q = $qb->update('\Application\User\Entity\User', 'u')
->set('u.password', $qb->expr()->literal($new_pass))
->where('u.userId = ?1')
->setParameter(1, "$userId")
->getQuery();
$p = $q->execute();
return $p;
}
The entity class should never utilize the entity manager. The entity class is just a data storage.
User entity class:
namespace Entity;
class User {
// ...
public function setPassword($password)
{
$this->password = some_hash_algorythm($password);
return $this;
}
// ...
}
Your controller or whereever you want to update a user's password:
$repo = $em->getRepository('Entity\User');
$user = $repo->find($userId);
$user->setPassword($newPassword);
$em->persist($user);
$em->flush();
This divides the data storage from actual persistence layer.
If you do not like to have the code in place and want to have it in a central place look in doctrine's documentation for custom repository classes (they are aware of the entity manager and there for "table-actions")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With