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

レッスン 15: 通知、メール、スケジューラ

通知チャネル (メール、データベース、Slack、SMS)。マークダウンメール、Mailables。タスクのスケジュール設定、カスタム アーティザン コマンド。 DTO の laravel-data。サービスコンテナの詳細。

💻 プログラミング — レッスン 15 レッスン 15: 通知、メール、スケジューラ

Laravel: 基本から上級まで

パート 4: 高度な機能

xdev.asia

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. カスタム アーティザン コマンド

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;
    }
}

次の記事: キャッシュ、セッション、パフォーマンス。