Мое решение для этой проблемы, которое работает.
<?php
namespace App\EventListener;
use App\Entity\Article;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Events;
use Twig\Environment;
class ArticleDeleteListener implements EventSubscriber
{
private $mailer;
private $twig;
public function __construct(\Swift_Mailer $mailer, Environment $twig)
{
$this->twig = $twig;
$this->mailer = $mailer;
}
public function getSubscribedEvents()
{
return [
Events::preRemove,
];
}
public function preRemove(LifecycleEventArgs $args)
{
$article = $args->getEntity();
if (!$article instanceof Article) {
return;
}
$emailAddress = $article->getAuthor()->getEmail();
$email = (new \Swift_Message())
->setFrom('send@example.com')
->setTo($emailAddress)
->setBody(
$this->twig->render('layouts/article/onDeleteEmail.html.twig', [
'article' => $article,
'author' => $article->getAuthor(),]
)
);
$this->mailer->send($email);
}
}
Services.yaml
App\EventListener\ArticleDeleteListener:
tags:
- { name: 'doctrine.event_listener', event: 'preRemove' }