Chuyển đến nội dung chính

第 15 課:通知、郵件和日程安排

通知頻道(郵件、資料庫、Slack、簡訊)。 Markdown 郵件,Mailables。任務調度、自訂 Artisan 命令。用於 DTO 的 laravel-data。服務容器深入研究。

💻 程式設計 — 第 15 課 第 15 課:通知、郵件和日程安排

Laravel:從基礎到高級

第 4 部分:進階功能

亞洲開發網

1. 通知

php artisan make:notification OrderShipped
class OrderShipped extends Notification implements ShouldQueue
{
    use Queueable;

    public function __construct(
        public readonly Order $order,
    ) {}

    public function via(object $notifiable): array
    {
        return ['mail', 'database'];
    }

    public function toMail(object $notifiable): MailMessage
    {
        return (new MailMessage)
            ->subject('Đơn hàng đã gửi')
            ->greeting('Xin chào ' . $notifiable->name)
            ->line('Đơn hàng #' . $this->order->id . ' đã được gửi.')
            ->action('Xem đơn hàng', url('/orders/' . $this->order->id))
            ->line('Cảm ơn bạn đã mua hàng!');
    }

    public function toArray(object $notifiable): array
    {
        return [
            'order_id' => $this->order->id,
            'message' => 'Đơn hàng #' . $this->order->id . ' đã gửi',
        ];
    }
}

// Gửi
$user->notify(new OrderShipped($order));
Notification::send($users, new OrderShipped($order));

2. 郵寄物品

class WelcomeMail extends Mailable
{
    use Queueable, SerializesModels;

    public function __construct(
        public readonly User $user,
    ) {}

    public function envelope(): Envelope
    {
        return new Envelope(subject: 'Chào mừng bạn!');
    }

    public function content(): Content
    {
        return new Content(markdown: 'emails.welcome');
    }

    public function attachments(): array
    {
        return [Attachment::fromPath('/path/guide.pdf')];
    }
}

Mail::to($user)->queue(new WelcomeMail($user));

3. 任務調度

// routes/console.php (Laravel 11)
Schedule::command('telescope:prune')->daily();
Schedule::command('reports:generate')->weeklyOn(1, '08:00');

Schedule::call(function () {
    DB::table('sessions')->where('last_activity', '<', now()->subHours(24))->delete();
})->hourly();

Schedule::job(new CleanupExpiredTokens)->everyFifteenMinutes();

4. 自訂 Artisan 指令

class GenerateReport extends Command
{
    protected $signature = 'report:generate {type} {--from= : Start date} {--to= : End date}';
    protected $description = 'Generate business reports';

    public function handle(): int
    {
        $type = $this->argument('type');
        $from = $this->option('from') ?? now()->startOfMonth()->toDateString();

        $this->info("Generating {$type} report from {$from}...");

        $bar = $this->output->createProgressBar(100);
        // ... process
        $bar->finish();

        $this->newLine();
        $this->info('Report generated successfully!');
        return Command::SUCCESS;
    }
}

下一篇: 緩存、會話和效能。