-2

我想做一个在删除时触发的事件。

当有人删除一篇文章时,我会从文章中获取用户电子邮件,并发送一封电子邮件,其中包含哪些文章被删除以及何时删除的信息。

我使用 Symfony 4 框架。

我不知道如何开始?

我有 CRUD 的文章控制器。

4

1 回答 1

0

我对这个问题的解决方案有效。

<?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);
    }
}

服务.yaml

App\EventListener\ArticleDeleteListener:
        tags:
            - { name: 'doctrine.event_listener', event: 'preRemove' }
于 2019-10-22T08:59:08.570 回答