繁体   English   中英

有人可以给我一个想法,如何在 Symfony4 中触发 onDelete(remove) 事件

[英]Can someone give me an Idea, how to make an event that is triggered onDelete(remove) in Symfony4

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

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

我使用 Symfony 4 框架。

我不知道如何开始?

我在文章 controller 中有 CRUD。

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

<?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' }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM