Laravel 事件、監聽與郵件通知
阿新 • • 發佈:2018-12-16
1、先繫結事件與監聽者:
app/Providers/EventServiceProvider.php
protected $listen = [
'App\Events\UserLogin' => [
'App\Listeners\MailAdminUserLogin',
],
]
2、並建立事件和監聽器:
PHP artisan event:generate
分別生成了2個檔案:app/Events/UserLogin.php和 app/Listeners/MailAdminUserLogin.php。
event:generate 命令省去了建立事件 make:event 和監聽者 make:listener 命令,並已經將事件與監聽做了關聯!
3、觸發事件,使用者登入控制器:
app/Http/Controllers/Auth/LoginController.php
改寫AuthenticatesUsers類:
... use App\Events\UserLogin; use Illuminate\Http\Request; ... /** * The user has been authenticated. * * @param \Illuminate\Http\Request $request * @param mixed $user * @return mixed */ protected function authenticated(Request $request,$user) { //dd($user); event(new UserLogin($user)); }
4、事件接收使用者引數
app/Events/UserLogin.php
use App\Models\User;
...
class UserLogin
{
...
public $user;
public function __construct(User $user)
{
$this->user=$user;
}
偵聽器
app/Listeners/MailAdminUserLogin.php:
public function handle(UserLogin $event) { dd($event); }
使用者註冊會列印使用者物件。
5、監聽器觸發郵件通知
app/Listeners/MailAdminUserLogin.php
...
use App\Notifications\MailTestNotification;
...
public function handle(UserLogin $event)
{
// dd($event);
new MailTestNotification($event);
}
有關郵件通知的類,請看這裡:https://blog.csdn.net/running8/article/details/84312630