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.
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
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;
}
}
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
}
}
Bạn có thể đăng ký event và listener trong app/Providers/EventServiceProvider.php:
protected $listen = [
OrderShipped::class => [
SendOrderShippedNotification::class,
],
];
Để kích hoạt event, bạn có thể gọi:
event(new OrderShipped($order));
Để đẩy listener vào hàng đợi, hãy triển khai ShouldQueue:
class SendOrderShippedNotification implements ShouldQueue
Bạn có thể chạy lệnh sau để kiểm tra tất cả event và listener đã đăng ký:
php artisan event:list