我希望这个问题不会重复。
在Laravel中,如何在match /users/{userId=**} {
文件之外向该事件注册事件/侦听器?另外,是否可以即时注册?
答案 0 :(得分:2)
您可以使用任何服务提供商的main()
方法注册事件,侦听器和订阅者。 main()
只是专门为事件提供了便利,但是它只是获取这些数组并对其进行旋转,并对其进行注册,无论如何您都将手动进行操作。
在框架基本上运行了服务提供者的所有int
方法之后,您可以随时注册事件和侦听器。
答案 1 :(得分:1)
我了解您在这里的沮丧。
我可以与您共享我的EventSubscriber,您只需在Event Provider中注册一次即可,一旦平台发展壮大,您就可以在该类中即时注册其他事件。
<?php
namespace App\Laravel\Jobs\Subscriber;
use App\Laravel\Models\{User,UserLogin,UserEngagement,UserDevice,UserPasswordReset};
use App\Laravel\Events\UserLogger;
use Illuminate\Contracts\Events\Dispatcher;
use Carbon,Mail,Str,DB;
class UserSubscriber
{
public function onResetPassword($data){
$user = $data->user;
$user_password = UserPasswordReset::where('email',$user->email)->first();
if(!$user_password){
$user_password = new UserPasswordReset;
$user_password->email = $user->email;
}
$user_password->token = Str::upper(Str::random(6));
$user_password->created_at = Carbon::now();
$user_password->save();
DB::commit();
$token = encrypt("{$user_password->email}__{$user_password->token}");
$input['token'] = $token;
Mail::send('emails.password', $input, function($message) use($user){
$message->to($user->email, $user->name)->subject("Password Reset Request");
});
}
public function registerDevice($data){
$user = $data->user;
if(strlen($data->device_id) > 0 AND strlen($data->device_reg_id) > 0){
$device = UserDevice::where('user_id',$user->id)
->where('device_id',$data->device_id)
->first();
if(!$device){
$device = new UserDevice;
$device->user_id = $user->id;
$device->device_id = $data->device_id;
}
$device->device_reg_id = $data->device_reg_id;
$device->device_brand = $data->device_brand;
$device->device_brand_model = $data->device_brand_model;
$device->device_platform = $data->device_platform;
$device->device_platform_version = $data->device_platform_version;
$device->is_login = 1;
$device->save();
}
}
/**
* @param User $user
*/
public function onLogin($data)
{
$user = $data->user;
$last_login = UserLogin::where('user_id',$user->id)->orderBy('created_at',"DESC")->first();
if(!$last_login OR ($last_login AND $last_login->created_at->diffInMinutes(Carbon::now()) >= 60)){
$login = new UserLogin;
$login->user_id = $user->id;
$login->ip_address = $data->ip_address;
$login->user_agent = $data->user_agent;
$login->save();
event('badge.login',(object)['user' => $user]);
}
}
/**
* Register the listeners for the subscriber.
*
* @param Dispatcher $events
*/
public function subscribe($events)
{
$events->listen(
'user.device',
'App\Laravel\Jobs\Subscriber\UserSubscriber@registerDevice'
);
$events->listen(
'user.login',
'App\Laravel\Jobs\Subscriber\UserSubscriber@onLogin'
);
$events->listen(
'user.reset_password',
'App\Laravel\Jobs\Subscriber\UserSubscriber@onResetPassword'
);
}
}
然后,在EventServiceProvider上,存在一个订阅变量,您可以在其中放置此UserSubscriber类
/**
* The subscriber classes to register.
*
* @var array
*/
protected $subscribe = [
\App\Laravel\Jobs\Subscriber\UserSubscriber::class,
];
这将为您节省大量工作,并可以更好地管理平台或项目中的事件