五步实现简单的 Laravel Events
最近使用了关于laravel events的相关知识,
events实现了一个简单的观察者模式,当某一件事情发生时,监听者listener就会触发某一时间。应用场景:注册成功发送邮件短信等,微信购买成功发送微信消息或图片。实现步骤如下:
- 在EventServiceProvider的$listen添加包含事件和监听对应的值,可以添加多条数组
<?php
namespace App\Providers;
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider{
/**- The event listener mappings for the application.
-
@var array
*/
protected $listen = [
'App\Events\UserLoggedIn' => [
'App\Listeners\WriteMessageToFile',
],
];/**
- Register any other events for your application.
- @param \Illuminate\Contracts\Events\Dispatcher $events
- @return void
*/
public function boot(DispatcherContract $events)
{
parent::boot($events);
}
}
- 运行
php artisan event:generate
- 找到要触发事件的代码,例如用户注册认证成功后要触发该事件,使用event()全局函数注册
protected function handleUserWasAuthenticated(Request $request, $throttles)
{
if ($throttles) {
$this->clearLoginAttempts($request);
}if (method_exists($this, 'authenticated')) { return $this->authenticated($request, Auth::guard($this->getGuard())->user()); } // Fire an event that the user has now logged in event(new UserLoggedIn($request)); return redirect()->intended($this->redirectPath());
}
- 更新事件类UserLoggedIn.php
<?php
namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Http\Request;
class UserLoggedIn extends Event{
use SerializesModels;
public $user;
/**- Create a new event instance.
-
@return void
*/
public function __construct(Request $request)
{
$this->request = $request;
}/**
- Get the channels the event should be broadcast on.
- @return array
*/
public function broadcastOn()
{
return [];
}
}
- 实现触发事件
<?php
namespace App\Listeners;
use App\Events\UserLoggedIn;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Storage;class WriteMessageToFile
{
/**- Create the event listener.
-
@return void
*/
public function __construct()
{
//
}/**
- Handle the event.
- @param UserLoggedIn $event
- @return void
*/
public function handle(UserLoggedIn $event)
{
$message = $event->request->user()->name . ' just logged in to the application.';
Storage::put('loginactivity.txt', $message);
}
}
推荐文章: