Laravel 私なりの自作ファサードの理解
背景
Slackで通知するにあたって、Laravel6でファサード作りました。
ここでまとめること
ファサード概要なので、ソースの細かい内容は割愛。
作ったファイルたち
# app\Facades\Slack.php <?php namespace App\Facades; use Illuminate\Support\Facades\Facade; class Slack extends Facade { protected static function getFacadeAccessor() { return 'slack'; } }
# app\Providers\SlackServiceProvider.php <?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use App\Services\SlackService; class SlackServiceProvider extends ServiceProvider { /** * Register services. * * @return void */ public function register() { $this->app->bind('slack', SlackService::class); } /** * Bootstrap services. * * @return void */ public function boot() { // } }
# app\Services\SlackService.php <?php namespace App\Services; use Illuminate\Notifications\Notifiable; use App\Notifications\SlackNotification; class SlackService { use Notifiable; /** * 通知チャンネル情報 * * @var array */ protected $channel = null; /** * 通知チャンネルを指定 * * @param array $channnel * @return this */ public function channel($channel) { $this->channel = config('slack.channels.' . $channel); return $this; } /** * Exceptionエラーを通知する * * @param string $message * @return void */ public function exceptAlert($message): void { $this->channel(config('slack.default')); } /** * 通知処理 * * @param string $message * @return void */ public function send($message = null) { if (!isset($this->channel)) { $this->channel(config('slack.default')); } $this->notify(new SlackNotification($this->channel, $message)); } /** * Slack通知用URLを指定する * * @return string */ protected function routeNotificationForSlack() { return config('slack.url'); } }
Facade を継承したクラスでは getFacadeAccessor
でファサードの名称(おそらく一意)を決める
ServiceProviderを継承したクラスで、ファサードの名称とサービスをバインドする。
これでファサードの登録が完了かな。
このサービスの中で、今回だったらSlackスラック通知クラスを作成する。このサービスクラスはLaravelに依存しないクラスなので自由にできそうね。