laravel 使用事件系统统计浏览量的实现
时间:2022-07-27
本文章向大家介绍laravel 使用事件系统统计浏览量的实现,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
最近有一个商城项目中有统计商品点击量和艺术家访问量的需求,但又不想改动太多原来的代码,而点击与访问这两个动作是有明确触发点的,正好可以用laravel中的事件系统来做,在点击和访问对应的函数中产生这俩事件,监视器获取到之后,再将记录保存到数据库中,并更新计数。
1、在 appProvidersEventServiceProvider
中注册监听器:
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
......
'AppEventsStatistics' = [
'AppListenersBehavioralStatistics',
],
......
];
2、执行
php artisan event:generate
生成事件类与监听类
3、定义事件
<?php
namespace AppEvents;
use IlluminateBroadcastingChannel;
use IlluminateQueueSerializesModels;
use IlluminateBroadcastingPrivateChannel;
use IlluminateBroadcastingPresenceChannel;
use IlluminateFoundationEventsDispatchable;
use IlluminateBroadcastingInteractsWithSockets;
use IlluminateContractsBroadcastingShouldBroadcast;
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 IlluminateBroadcastingChannel|array
*/
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}
4、定义监听器:
<?php
namespace AppListeners;
use AppEventsStatistics;
use AppSystemStaticsView;
use IlluminateQueueInteractsWithQueue;
use IlluminateContractsQueueShouldQueue;
use IlluminateSupportFacadesLog;
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 "AppUser":
$statics_view- statics_type = 'user';
break;
case "AppProduction":
$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));
以上这篇laravel 使用事件系统统计浏览量的实现就是小编分享给大家的全部内容了,希望能给大家一个参考。
- php概述
- php教程
- php环境搭建
- PHP书写格式
- php变量
- php常量
- PHP注释
- php数组
- php字符串 string
- PHP整型 integer
- PHP浮点型 float
- php布尔型
- php数据类型之数组
- php数据类型之对象
- php数据类型之null
- php数据类型之间的转换
- php运算符
- php表达式
- PHP循环控制
- PHP流程控制
- php函数
- php全局变量
- PHP魔术变量
- php命名空间
- php 日期
- PHP包含文件
- php文件
- PHP 文件上传
- php Cookies
- php Sessions
- php email
- php安全email
- php错误处理
- PHP异常处理
- php过滤器
- PHP 高级过滤器
- php json
- php 表单
- PHP MySQL 简介
- PHP 连接 MySQL
- php创建数据库
- php 创建表
- php mysq 插入数据
- PHP MySQL 插入多条数据
- PHP MySQL 预处理语句
- php mysql 读取数据
- php mysql where
- PHP MySQL Order By
- PHP MySQL Update
- PHP MySQL Delete
- php ODBC