Events trong Laravel

1. Giới Thiệu

Laravel cung cấp hệ thống sự kiện (Event) mạnh mẽ giúp bạn có thể xử lý các hành động không đồng bộ hoặc tách rời các phần logic của ứng dụng. Ví dụ: gửi email sau khi người dùng đăng ký hoặc ghi log khi đơn hàng được đặt thành công.

2. Tạo Event và Listener

Bạn có thể tạo một event bằng Artisan command:

php artisan make:event OrderShipped

Tương tự, để tạo một listener:

php artisan make:listener SendOrderShippedNotification --event=OrderShipped

3. Định Nghĩa Event

Mỗi event được lưu trong app/Events và chứa các thuộc tính cần thiết để truyền dữ liệu:


namespace App\Events;

use Illuminate\Foundation\Events\Dispatchable;

class OrderShipped
{
    use Dispatchable;
    
    public $order;

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

4. Định Nghĩa Listener

Mỗi listener được lưu trong app/Listeners và xử lý sự kiện khi nó được kích hoạt:


namespace App\Listeners;

use App\Events\OrderShipped;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendOrderShippedNotification implements ShouldQueue
{
    public function handle(OrderShipped $event)
    {
        // Gửi thông báo hoặc email
    }
}
                

5. Đăng Ký Event và Listener

Bạn có thể đăng ký event và listener trong app/Providers/EventServiceProvider.php:


protected $listen = [
    OrderShipped::class => [
        SendOrderShippedNotification::class,
    ],
];
                

6. Kích Hoạt Event

Để kích hoạt event, bạn có thể gọi:

event(new OrderShipped($order));

7. Xử Lý Queue trong Listener

Để đẩy listener vào hàng đợi, hãy triển khai ShouldQueue:

class SendOrderShippedNotification implements ShouldQueue

8. Xem Danh Sách Event

Bạn có thể chạy lệnh sau để kiểm tra tất cả event và listener đã đăng ký:

php artisan event:list