[Laravel] Event, Listener, Notification 을 활용한 메일 보내기

[Laravel] Event, Listener, Notification 을 활용한 메일 보내기 updated_at: 2024-10-22 17:47

Event, Listener, Notification 을 활용한 메일 보내기

이번장은 이벤트, 리스너 및 노티피케이션을 한쌍으로 하여 간단한 메일을 발송하는 프로그램을 설명드릴 예정입니다.
이전장에서 Event, Listener 처리하기에서 설명드린 것과 유사하지만 여기서는 한 번더 심층적으로 설명드리겠습니다.
먼저 전체 flow는 특정 프로세스에서 Event를 호출하고 그것을 리스너가 subscriber 하다가 notification으로 전달하여 메일을 보냅니다.

아래 예제는 주문서를 발송하는 예제입니다.

1. Event 파일 생성

여기서는 두가지 인자값 $user(회원정보) 및 $order(주문정보)를 받습니다.

  • app > Events > OrderShipped.php
class OrderShipped
{
  public $order;
  public $user;

  public function __construct($user, $order)
  {
    $this->user = $user;
    $this->order = $order;
  }
}

2. Listener 파일 생성

  • app > Listeners > OrderEventSubscriber.php
use App\Events\OrderShipped;
use App\Notifications\OrderShippedNotification; // 아래 3번에서 정의
class OrderEventSubscriber
{
  /**
  *@paramas Object $event : OrderShipped 에 public으로 정의된 {user, order 값이 넘어옮}
  */
  public function ordered($event) {
    $event->user->notify(new OrderShippedNotification($event->order));
    // 위의 경우는 user Model에서   Notifiable 이 정의된 경우이고 그렇지 않은 경우 아래와 같이 사용한다.
    // \Illuminate\Support\Facades\Notification\Notification::send($event->user, new OrderShippedNotification($event->order));
  }

  public function subscribe($events)
  {
    return [
      OrderShipped::class => 'ordered', // OrderShipped Event가 발생하면 위에 정의된 ordered로 보냄
    ];
  }
}

2. 1 Event파일과 Listener 파일 열결하기

이벤트가 발생할때 Listener에서 subscribe 하기위해서는 EventServiceProvider 에 아래와 같이 설정해 두어야 한다.

  • app/Providers/EventServiceProvider.php
use App\Listeners\OrderEventSubscriber;
..........
class EventServiceProvider extends ServiceProvider
{
  ..........
  protected $subscribe = [
    OrderEventSubscriber::class,
  ];

}

3. Notification 파일 생성

OrderShippedNotification.php 에서 $notifiable 이라는 변수에 대해서 궁금할 것입니다.
위의 $event->user->notify(new OrderShippedNotification($event->order)); 구문에서 notify하는 대상인 $event->user 가 $notifiable 에 나타납니다.

  • app > Notifications > OrderShippedNotification.php
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class OrderShippedNotification extends Notification  implements ShouldQueue // implements ShouldQueue 정의시 비동기식으로 job테이블등에 데이타가 들어가서 처리됨
{
  use Queueable;


  protected $order;
  public function __construct($order)
  {
    $this->order = $order;
  }

  public function via($notifiable)
  {
    return ['mail']; // 전송방식 정의, mail일 경우 아래 toMail 에서 데이타를 받음
  }

  public function toMail($notifiable)
  {
    return (new MailMessage)
      ->subject('주문정보입니다.')
      ->view('order', [
        'user' => $notifiable,
        'data' => $data
      ]);
  }
}

4. 이벤트 호출하기

use App\Events\OrderShipped;
..........
event(new OrderShipped($user, $order));
평점을 남겨주세요
평점 : 5.0
총 투표수 : 1

질문 및 답글