0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Symfonyでevent & event listenerを実装する

0
Posted at

Event & Event Listener とは

Eventとはアプリケーションの中で何かが起きたことを表現します。
そしてEvent Listenerとはそのイベントの発生を待ち、そのイベントが発生した時に何か動作を行います。
今回はEventとEvent ListenerをSymfonyで実装してみます。

Symfony のEvent機構

symfonyにはeventの機構が存在します。
https://symfony.com/doc/current/event_dispatcher.html

実装例

例として記事の投稿ができるブログを想定します。
記事が投稿されたとき、ログに新規記事が投稿された旨を追記するとします。
この場合では「記事が投稿された」というEventがディスパッチされてそのEventを待っているEvent Listenerがログに書き込む処理を行います。

Eventクラス

PostPublishedEvent.php
<?php

namespace App\Event;

use App\Entity\Post;
use Symfony\Contracts\EventDispatcher\Event;

/**
 * 記事のステータスが "published" になったときに発火するイベント。
 */
final class PostPublishedEvent extends Event
{
    public function __construct(
        private readonly Post $post,
    ) {}

    public function getPost(): Post
    {
        return $this->post;
    }
}

Event Listener クラス

PostNotificationListener.php
<?php

namespace App\EventListener;

use App\Event\PostPublishedEvent;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;

/**
 * 記事公開時に通知(ここではログ)を送るリスナー。
 */
#[AsEventListener(event: PostPublishedEvent::class)]
final class PostNotificationListener
{
    public function __construct(
        private readonly LoggerInterface $logger,
    ) {}

    public function __invoke(PostPublishedEvent $event): void
    {
        $post = $event->getPost();

        $this->logger->info('記事が公開されました: "{title}" (著者: {author})', [
            'title' => $post->getTitle(),
            'author' => $post->getAuthor()?->getDisplayName() ?? '不明',
            'slug' => $post->getSlug(),
        ]);
    }
}

Event を発行したいクラスでEventをdispatchします。
今回はコントローラでdispatchするとします。

コントローラ

PostController.php
<?php

namespace App\Controller;

use App\Entity\Post;
use App\Event\PostCreatedEvent;
use App\Event\PostPublishedEvent;
use App\Form\PostType;
use App\Repository\PostRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
use Symfony\Component\String\Slugger\SluggerInterface;

#[Route('/admin/posts')]
final class PostController extends AbstractController
{

    #[Route('/new', name: 'app_post_new', methods: ['GET', 'POST'])]
    public function new(
        Request $request,
        EntityManagerInterface $entityManager,
        SluggerInterface $slugger,
        EventDispatcherInterface $dispatcher
    ): Response {
        $post = new Post();
        $form = $this->createForm(PostType::class, $post);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $post->setAuthor($this->getUser());
            $post->setSlug(
                $slugger->slug($post->getTitle())->lower()->toString()
            );

            // イベントをディスパッチする
            $dispatcher->dispatch(new PostPublishedEvent($post)); 
            
            $entityManager->persist($post);
            $entityManager->flush();

            return $this->redirectToRoute('app_post_index', [], Response::HTTP_SEE_OTHER);
        }

        return $this->render('post/new.html.twig', [
            'post' => $post,
            'form' => $form,
        ]);
    }

}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?