I want to register Doctrine Event Listener to hash user's password before persisting User
object to database:
This is my Event Listener class:
<?php
namespace AppBundle\Doctrine;
use AppBundle\Entity\User;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
class HashPasswordListener implements EventSubscriber
{
private $passwordEncoder;
public function __construct(UserPasswordEncoderInterface $passwordEncoder)
{
$this->passwordEncoder = $passwordEncoder;
}
public function getSubscribedEvents()
{
return ['prePersist', 'preUpdate'];
}
public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if (!$entity instanceof User) {
return;
}
$this->encodePassword($entity);
}
/**
* @param User $entity
*/
private function encodePassword(User $entity)
{
$encoded = $this->passwordEncoder->encodePassword($entity, $entity->getPlainPassword());
$entity->setPassword($encoded);
}
public function preUpdate(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if (!$entity instanceof User) {
return;
}
$this->encodePassword($entity);
}
}
And I register this event listener in services.yml
file
AppBundle\Doctrine\HashPasswordListener:
tags: ['doctrine.event_listener']
But whenever I want to insert a user either by loading fixtures data or from the web application I receive such an error:
[Symfony\Component\DependencyInjection\Exception\InvalidArgumentException]
Doctrine event listener "AppBundle\Doctrine\HashPasswordListener" must specify the "event" attribute.
I tried to add event attribute in tags
that didn't work either.
I'm using Symfony version 3.3 with Doctrine 2.5
Configured Doctrine in config.yml
so:
doctrine:
dbal:
driver: pdo_sqlite
path: '%kernel.project_dir%/app/sqlite.db'
charset: UTF8
Where is the fault?
you use un subscriber so you must tag doctrine event subscriber not event listener that requires attribute event.
AppBundle\Doctrine\HashPasswordListener:
tags: ['doctrine.event_subscriber']