Symfony 4 Event Subscriber Kullanımı

JSON olarak gelen kullanıcı kayıt bilgilerini veritabanına yazmadan önce parolayı şifrelememiz gerekiyor. Bunu Event subscriber ile her kullanıcı kayıt olduğunda otomatik yapmasını sağlayabiliriz. Ayrıca aynı şekilde kayıt sonrası doğrulama mailinin gönderilmesini de bu şekilde yapabiliriz.

src/EventSubscriber klasörünü açıp içine PasswordHashSubscriber.php dosyamızı oluşturuyoruz.

 

[php]

namespace App\EventSubscriber;

use App\Entity\User;
use Doctrine\Common\EventSubscriber;
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

class PasswordHashSubscriber implements EventSubscriber
{
private $encoder;

public function __construct(UserPasswordEncoderInterface $encoder)
{
$this->encoder = $encoder;
}

public function getSubscribedEvents()
{

return [‘prePersist’];

}

public function prePersist(LifecycleEventArgs $args )
{

$user = $args->getObject();
if ($user instanceof User) {
$encoded = $this->encoder->encodePassword($user, $user->getPassword());
$user->setPassword($encoded);
}
}

}
[/php]

Daha sonra istediğimiz yerde subscriber eklemesini yapabiliriz. Ben kullanıcı kayıt fonksiyonunun olduğu yerde bu işlemi yaptım.

[php]
// $encoder değişkeni => UserPasswordEncoderInterface $encoder olarak fonksiyon parametresinden geliyor.
$entityManager->getEventManager()->addEventSubscriber(new PasswordHashSubscriber( $encoder ));
[/php]

Eğer otomatik olarak her yerde çalışsın derseniz . config/services.yaml dosyasına aşağıdaki kodu ekleyebilirsiniz.

[php]
App\EventSubscriber\PasswordHashSubscriber:
tags:
– { name : doctrine.event_subscriber, connection: default}
[/php]

Cem Karakurt: