"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > 알림 및 작업 처리를 중앙 집중화하세요

알림 및 작업 처리를 중앙 집중화하세요

2024-11-08에 게시됨
검색:200

Centralize your notification and job handling

다양한 이벤트(예: 사용자 생성, 비밀번호 재설정 등) 이후 여러 이메일 알림 전송을 단순화하려면 몇 가지 단계를 수행하여 알림 및 작업 처리를 중앙 집중화할 수 있습니다.. 이 접근 방식을 사용하면 각 이벤트에 대해 별도의 작업이나 알림을 만들지 않고도 작업이 더 쉽고 확장 가능해집니다.

이메일 알림 처리를 단순화하기 위한 전략:

  1. 일반화된 이메일 알림 작업을 사용합니다.
  2. 이벤트 리스너 아키텍처 활용.
  3. 그룹 유사 알림.

1. 일반 이메일 알림 작업 생성:

각 알림에 대해 별도의 작업을 만드는 대신 알림과 사용자를 매개변수로 사용하는 재사용 가능한 단일 작업을 만들 수 있습니다. 이렇게 하면 동일한 작업을 사용하여 다양한 알림을 처리할 수 있습니다.

일반화된 SendEmailNotificationJob:

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Notifications\Notification;
use App\Models\User;

class SendEmailNotificationJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $user;
    public $notification;

    /**
     * Create a new job instance.
     *
     * @param  User $user
     * @param  Notification $notification
     * @return void
     */
    public function __construct(User $user, Notification $notification)
    {
        $this->user = $user;
        $this->notification = $notification;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // Send the notification
        $this->user->notify($this->notification);
    }
}

이 일반화된 작업을 사용하면 동일한 작업을 사용하여 다양한 유형의 이메일 알림을 전달할 수 있습니다.

사용 예:

use App\Jobs\SendEmailNotificationJob;
use App\Notifications\UserWelcomeNotification;
use App\Models\User;

$user = User::find(1); // Example user

// Dispatch a welcome email notification
SendEmailNotificationJob::dispatch($user, new UserWelcomeNotification());

// Dispatch a password reset notification
SendEmailNotificationJob::dispatch($user, new PasswordResetNotification());

2. 이벤트 리스너 아키텍처 활용:

각 이벤트 후에 수동으로 작업을 디스패치하는 대신, Laravel의 이벤트 리스너 아키텍처를 사용하면 특정 이벤트(예: 사용자 생성)를 기반으로 알림 및 작업을 자동으로 트리거할 수 있습니다.

1단계: 이벤트 정의:

UserCreated와 같은 이벤트를 정의할 수 있습니다:

php artisan make:event UserCreated

UserCreated 이벤트 예:

namespace App\Events;

use App\Models\User;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class UserCreated
{
    use Dispatchable, SerializesModels;

    public $user;

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

2단계: 리스너 생성:

이벤트가 시작될 때 알림을 보내는 리스너를 만들 수 있습니다.

php artisan make:listener SendUserWelcomeNotification --event=UserCreated

예제 리스너:

namespace App\Listeners;

use App\Events\UserCreated;
use App\Jobs\SendEmailNotificationJob;
use App\Notifications\UserWelcomeNotification;

class SendUserWelcomeNotification
{
    public function handle(UserCreated $event)
    {
        // Dispatch the email notification job
        SendEmailNotificationJob::dispatch($event->user, new UserWelcomeNotification());
    }
}

3단계: 사용자 생성 시 이벤트 발생:

사용자가 생성될 때마다 이벤트를 실행할 수 있으며 Laravel이 자동으로 나머지를 처리합니다.

use App\Events\UserCreated;

$user = User::create($data);
event(new UserCreated($user));

이 접근 방식을 사용하면 알림 처리 논리를 비즈니스 논리에서 분리하여 시스템 확장성을 높일 수 있습니다.

3. 비슷한 알림 그룹화:

유사한 알림(예: 환영 이메일, 비밀번호 재설정 등과 같은 사용자 관련 알림)이 많은 경우 모든 사용자 알림을 중앙 집중식으로 처리하는 알림 서비스를 만들 수 있습니다.

예 알림 서비스:

namespace App\Services;

use App\Models\User;
use App\Jobs\SendEmailNotificationJob;
use App\Notifications\UserWelcomeNotification;
use App\Notifications\PasswordResetNotification;

class NotificationService
{
    public function sendUserWelcomeEmail(User $user)
    {
        SendEmailNotificationJob::dispatch($user, new UserWelcomeNotification());
    }

    public function sendPasswordResetEmail(User $user)
    {
        SendEmailNotificationJob::dispatch($user, new PasswordResetNotification());
    }

    // You can add more methods for different types of notifications
}

사용 예:

컨트롤러나 이벤트 리스너에서 이제 간단히 서비스를 호출할 수 있습니다.

$notificationService = new NotificationService();
$notificationService->sendUserWelcomeEmail($user);

결론:

  • 단일 작업: 일반화된 작업(SendEmailNotificationJob)을 사용하여 다양한 유형의 알림을 처리할 수 있습니다.
  • 이벤트 리스너 아키텍처: Laravel의 이벤트 리스너 시스템을 활용하여 시스템 이벤트에 기반한 알림을 자동으로 트리거합니다.
  • 중앙 집중식 알림 서비스: 더 나은 관리 및 재사용성을 위해 유사한 알림을 하나의 서비스로 그룹화합니다.

이 접근 방식은 코드를 DRY(반복하지 마세요) 상태로 유지하는 데 도움이 되며 보낼 이메일 알림이 여러 개 있을 때 유지 관리가 더 쉬워집니다.

릴리스 선언문 이 글은 https://dev.to/msnmongare/centralize-your-notification-and-job-handling-1oid?1에서 복제됩니다.1 침해 내용이 있는 경우, [email protected]으로 연락하여 삭제하시기 바랍니다.
최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3