laravel 使用事件系统统计浏览量的实现
最近有一个商城项目中有统计商品点击量和艺术家访问量的需求,但又不想改动太多原来的代码,而点击与访问这两个动作是有明确触发点的,正好可以用laravel中的事件系统来做,在点击和访问对应的函数中产生这俩事件,监视器获取到之后,再将记录保存到数据库中,并更新计数。
1、在app\Providers\EventServiceProvider
中注册监听器:
/** *Theeventlistenermappingsfortheapplication. * *@vararray */ protected$listen=[ ...... 'App\Events\Statistics'=>[ 'App\Listeners\BehavioralStatistics', ], ...... ];
2、执行
phpartisanevent:generate
生成事件类与监听类
3、定义事件
user=$user;
$this->obj=$obj;
}
/**
*Getthechannelstheeventshouldbroadcaston.
*
*@return\Illuminate\Broadcasting\Channel|array
*/
publicfunctionbroadcastOn()
{
returnnewPrivateChannel('channel-name');
}
}
4、定义监听器:
obj);
$statics_view=newStaticsView;
switch($obj_class){
case"App\\User":
$statics_view->statics_type='user';
break;
case"App\\Production":
$statics_view->statics_type='production';
break;
}
$statics_view->ip=request()->getClientIp();;
$statics_view->time_local=0;
$statics_view->statics_id=$event->obj->id;
$statics_view->save();
}
}
5、触发事件:
event(newStatistics(user,user,user,production));
以上这篇laravel使用事件系统统计浏览量的实现就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。