Laravel 事件、监听与邮件通知

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

 

 

 

你可能感兴趣的:(PHP,Laravel)