說明:本文主要學習Laravel的Artisan Command、Task Scheduler和Mail相關知識。做一個簡單的小demo,用來定時發郵件。。走完整個流程最多隻需一小時。同時,作者會將開發過程中的一些和代碼黏上去,提高閱讀效率。作者的開發環境是原生MAMP整合軟體,PHP7.0,Laravel5.2.*。
Laravel中Artisan Command內容可以參看: 服務 —— Artisan Console ,Mail郵件服務內容可以參看: 服務 —— 郵件 ,以及Task-Scheduler任務定時器可以參看: 服務 —— 任務調度 。
Artisan Command
建立一個artisan command:
php artisan make:console SendEmails --command=emails:send
並在AppConsoleCommandsSendEmails.php檔案中添加代碼:
class SendEmails extends Command{ /** * The name and signature of the console command. * * @var string */ protected $signature = 'emails:send'; /** * The console command description. * * @var string */ protected $description = 'This is a demo about sending emails to myself'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $this->info('I am handsome'); $this->error('I am not ugly'); }}
寫上$description和handle()方法,$description變數用來顯示命令的說明,handle()用來處理命令,然後在AppConsoleCommandsKernel.php中註冊命令:
protected $commands = [ // Commands\Inspire::class, Commands\SendEmails::class, ];
好,這下可以在終端輸入php artisan查看並執行命令了:
Mail
郵件服務API驅動需要安裝guzzlehttp/guzzle這個包,在項目根目錄下:
composer require guzzlehttp/guzzle
然後在.env檔案中配置下郵件驅動和使用者名稱密碼:
然後修改下handle()方法:
/** * Execute the console command. * * @return mixed */ public function handle() {// $this->info('I am handsome');// $this->error('I am not ugly'); $user = [ 'email' => 'XXX@XXX.com',//一個有效郵箱接收地址 'name' => 'liuxiang', ]; $status = Mail::send('emails.send', ['user'=>$user], function($msg) use ($user){ $msg->from('XXX@XXX.com', 'liuxiang email');//一個有效郵箱發送地址 $msg->to($user['email'], $user['name'])->subject('This is a demo about sending emails to myself'); }); if(!$status){ $this->error('Fail to send email');exit; } $this->info('Success to send email');exit; }
發送的內容在視圖emails.send裡,建立resources/views/emails/send.blade.php檔案:
Bootstrap Template This is a email by Laravel Artisan Command
一切準備OK,在項目根目錄運行郵件發送命令吧,然後會收到郵件發送成功列印:
然後接收的郵箱會收到郵件:
It is working!!!
Task-Scheduler
每次手動發郵件畢竟不太爽啊,可以利用系統的定時器crontab定時發送,Laravel裡有任務定時器可以玩一玩。修改app/Console/Kernel.php檔案:
/** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ protected function schedule(Schedule $schedule) { // $schedule->command('inspire')->hourly(); //$schedule->command('emails:send')->everyFiveMinutes(); $schedule->command('emails:send')->everyMinutes(); }
在終端輸入 crontab -e 添加一個cron條目:
* * * * * php /Applications/MAMP/htdocs/laravelemail/artisan schedule:run 1>> /dev/null 2>&1
然後程式每隔一分鐘發個郵件過來:
總結:本文主要以Laravel的Artisan Command、Mail和Task-Scheduler做一個好玩的小demo,來定時發發騷擾郵件,哈哈。還挺好玩的,可以試一試。。嘛,過幾天想結合設計模式來聊聊Laravel,到時見。