概要
Laravel5.3からNotifications - Laravel - The PHP Framework For Web Artisans が追加され、ユーザ通知機能がたいへん簡単に実装できるようになりました。
今回はhttp://localhost:8000
にアクセスされたらSlackにメッセージを飛ばすという簡単な機能を実装します。
Laravel5.3のインストール
-
GithubのリポジトリからDL
-
DL後、
composer update
を実行- PHP5.6以降じゃないとcomposer updateできないので注意
Guzzleを追加する
- Guzzleとは
- PHPのHTTPクライアントライブラリ
- DLしたLaravelのディレクトリの直下で下記のコマンドを実行し、パッケージを追加する
$ composer require guzzlehttp/guzzle
Notificationクラスの作成
- artisanコマンドでNotificationクラスを生成する
- app/Notifications/SlackPosted.php
$ php artisan make:notification SlackPosted
Notification created successfully.
Notificationクラスの修正
通知するサービスの追加
- viaメソッドを編集する
- 通知するサービス名にslackを追加する
app/Notifications/SlackPosted.php
<?php
class SlackPosted extends Notification
{
public function via($notifiable)
{
return ['slack'];
}
}
Slackに通知するメッセージの作成
app/Notifications/SlackPosted.php
use Illuminate\Notifications\Messages\SlackMessage;
public function toSlack($notifiable)
{
return (new SlackMessage)
->success()
->content('問題が発生しました')
->attachment(function ($attachment) {
$attachment->title('weeklyランキングが生成されませんでした。')
->content('エラーログ。。。');
});
}
上記の記述で実際にSlackに通知されるメッセージはこんな感じ。
routeNotificationForSlackメソッドの追加
- SlackのWebHook URLを返すrouteNotificationForSlackメソッドを追加する
- routeNotificationForXXX
- XXXの部分書かれたサービス名をもとに、Laravelが自動的にドライバ情報を読み込んでくれる
app/User.php
public function routeNotificationForSlack()
{
return 'https://hooks.slack.com/services/xxxx/xxxx/xxxx';
}
ルーティングの修正
-
/
にアクセスがあった時にnotifyメソッドでユーザに通知する - notifyメソッドはNotificationクラスのインスタンスを受け取り、通知する
routes/web.php
Route::get('/', function () {
$user = new App\User;
$user->notify(new \App\Notifications\SlackPosted);
});
あとはphp artisan serve
で起動し、http://localhost:8000
にアクセスするとSlackにメッセージが届くはずです!
参考記事
リリース直前! Laravel 5.3 の変更点(新機能編)
http://tech.innovator.jp.net/entry/2016/08/17/115629
Send Slack Notifications With Laravel in Minutes
https://laracasts.com/series/whats-new-in-laravel-5-3/episodes/11
Notifications - Laravel - The PHP Framework For Web Artisans
https://laravel.com/docs/5.3/notifications