laravel 使用事件系统统计浏览量的实现
发布:smiling 来源: PHP粉丝网 添加日期:2022-01-06 10:36:08 浏览: 评论:0
今天小编就为大家分享一篇laravel 使用事件系统统计浏览量的实现,具有很好的参考价值,希望对大家有所帮助,一起跟随小编过来看看吧。
最近有一个商城项目中有统计商品点击量和艺术家访问量的需求,但又不想改动太多原来的代码,而点击与访问这两个动作是有明确触发点的,正好可以用laravel中的事件系统来做,在点击和访问对应的函数中产生这俩事件,监视器获取到之后,再将记录保存到数据库中,并更新计数。
1、在 app\Providers\EventServiceProvider中注册监听器:
- /**
- * The event listener mappings for the application.
- *
- * @var array
- */
- protected $listen = [
- ......
- 'App\Events\Statistics' => [
- 'App\Listeners\BehavioralStatistics',
- ],
- ......
- ];
2、执行
php artisan event:generate
生成事件类与监听类
3、定义事件
- <?php
- namespace App\Events;
- use Illuminate\Broadcasting\Channel;
- use Illuminate\Queue\SerializesModels;
- use Illuminate\Broadcasting\PrivateChannel;
- use Illuminate\Broadcasting\PresenceChannel;
- use Illuminate\Foundation\Events\Dispatchable;
- use Illuminate\Broadcasting\InteractsWithSockets;
- use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
- class Statistics
- {
- use Dispatchable, InteractsWithSockets, SerializesModels;
- public $user;
- public $obj;
- /**
- * Create a new event instance.
- *
- * @return void
- */
- public function __construct($user,$obj)
- {
- $this->user = $user;
- $this->obj = $obj;
- }
- /**
- * Get the channels the event should broadcast on.
- *
- * @return \Illuminate\Broadcasting\Channel|array
- */
- public function broadcastOn()
- {
- return new PrivateChannel('channel-name');
- }
- }
4、定义监听器:
- <?php
- namespace App\Listeners;
- use App\Events\Statistics;
- use App\System\StaticsView;
- use Illuminate\Queue\InteractsWithQueue;
- use Illuminate\Contracts\Queue\ShouldQueue;
- use Illuminate\Support\Facades\Log;
- class BehavioralStatistics
- {
- /**
- * Create the event listener.
- *
- * @return void
- */
- public function __construct()
- {
- //
- }
- /**
- * Handle the event.
- *
- * @param Statistics $event
- * @return void
- */
- public function handle(Statistics $event)
- {
- $obj_class = get_class($event->obj);
- $statics_view = new StaticsView;
- 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(new Statistics(user, user,user,production));
Tags: laravel事件系统 laravel浏览量
推荐文章
热门文章
最新评论文章
- 写给考虑创业的年轻程序员(10)
- PHP新手上路(一)(7)
- 惹恼程序员的十件事(5)
- PHP邮件发送例子,已测试成功(5)
- 致初学者:PHP比ASP优秀的七个理由(4)
- PHP会被淘汰吗?(4)
- PHP新手上路(四)(4)
- 如何去学习PHP?(2)
- 简单入门级php分页代码(2)
- php中邮箱email 电话等格式的验证(2)