mafrasil/laravel-sonar 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

mafrasil/laravel-sonar

Composer 安装命令:

composer require mafrasil/laravel-sonar

包简介

Product analytics

README 文档

README

Latest Version on Packagist GitHub Tests Action Status Total Downloads

Laravel Sonar is a powerful product analytics package that makes it easy to track user interactions in your Laravel application. It provides automatic tracking for clicks, hovers, and impressions, with support for custom events.

Features

  • 🚀 Automatic event tracking (clicks, hovers, impressions)
  • 🎯 Custom event tracking
  • ⚡ Efficient batch processing of events
  • 🛠️ Optional React components and hooks for easy integration
  • 📱 Responsive design support with screen size tracking
  • 🔄 Compatible with Inertia.js
  • ⚙️ Configurable tracking behavior

Installation

You can install the package via composer:

composer require mafrasil/laravel-sonar

Then install the package and publish the assets:

php artisan sonar:install
php artisan vendor:publish --tag=sonar-assets

This will publish the config file, assets and run the migrations.

You can also publish the config file, assets and run the migrations separately:

php artisan vendor:publish --tag=sonar-config # Publish the config file
php artisan vendor:publish --tag=sonar-assets # Publish the assets
php artisan vendor:publish --tag=sonar-migrations # Publish the migrations
php artisan migrate # Run the migrations

You can also publish the views of the dashboard:

php artisan vendor:publish --tag=sonar-views

Optional: Export React Components

If you're using React, you can export the React components and TypeScript types:

php artisan sonar:export-react

This will create React components and hooks in your application's JavaScript directory.

Usage

Data Attributes

The simplest way to track elements is using data attributes:

<button data-sonar="signup-button" data-sonar-metadata='{"variant": "blue"}'>
    Sign Up
</button>

React Component (Optional)

If you've exported the React components, you can use the SonarTracker component:

import { SonarTracker } from "@/components/SonarTracker";

function SignupButton() {
    return (
        <SonarTracker
            name="signup-button"
            metadata={{ variant: "blue" }}
            trackAllHovers={true} // Optional: track repeated hovers
        >
            <button>Sign Up</button>
        </SonarTracker>
    );
}

Custom Events

Use the useSonar hook for custom event tracking and configuration:

import { useSonar } from "@/hooks/useSonar";

function CheckoutForm() {
    const { track, configure } = useSonar();

    // Optional: Configure tracking behavior
    useEffect(() => {
        configure({ trackAllHovers: true });
    }, []);

    const handleSubmit = () => {
        track("checkout-complete", "custom", {
            amount: 99.99,
            currency: "USD",
        });
    };

    return <form onSubmit={handleSubmit}>{/* form fields */}</form>;
}

Server-Side Tracking

You can also track events from your PHP code:

use Mafrasil\LaravelSonar\Facades\LaravelSonar;

LaravelSonar::track('order-processed', 'custom', [
    'orderId' => $order->id,
    'amount' => $order->total
]);

Event Types

The package supports the following event types out of the box:

  • click: User clicks on tracked elements
  • hover: User hovers over tracked elements (configurable for repeated tracking)
  • impression: Element becomes visible in the viewport
  • custom: Any custom event you want to track

Configuration

You can customize the package behavior in the config/sonar.php file:

return [
    'route' => [
        'prefix' => 'api',
        'middleware' => ['api'],
    ],
    'queue' => [
        'batch_size' => 10,
        'flush_interval' => 1000,
    ],
    // ...
];

JavaScript Configuration

You can configure the JavaScript behavior globally:

import { configureSonar } from "laravel-sonar";

configureSonar({
    trackAllHovers: true, // Enable tracking of repeated hovers
});

Analytics

Laravel Sonar provides several methods to analyze your collected data. You can use these methods to build dashboards or generate reports.

Available Methods

use Mafrasil\LaravelSonar\Facades\LaravelSonar;

// Get events grouped by type
$eventsByType = LaravelSonar::getEventsByType(
    startDate: now()->subDays(7), // optional
    endDate: now() // optional
);

// Get most active pages
$topPages = LaravelSonar::getTopPages(
    limit: 10, // optional, defaults to 10
    startDate: now()->subDays(30) // optional
);

// Get event timeline
$timeline = LaravelSonar::getEventTimeline(
    interval: '1 day', // optional, defaults to '1 day'
    startDate: now()->subDays(30) // optional
);

// Get most triggered events
$topEvents = LaravelSonar::getTopEvents(
    limit: 10, // optional, defaults to 10
    type: 'click' // optional, filter by event type
);

// Get user engagement metrics
$engagement = LaravelSonar::getUserEngagement();

Dashboard & Analytics

CLI Analytics

The package includes a convenient command-line interface for quick analytics overview:

php artisan sonar:stats --limit=20

This is particularly useful for quick analytics checks or automated reporting scripts.

Access Control

By default, the Sonar dashboard is only accessible in the local environment.

You can enable it anytime by setting the SONAR_DASHBOARD_ENABLED environment variable to true.

To allow specific users in other environments, configure the allowed emails in your config/sonar.php:

'allowed_emails' => [
    'user@example.com',
],

You can also customize the authorization logic by overriding the viewSonar gate in your AuthServiceProvider:

use Illuminate\Support\Facades\Gate;
public function boot()
{
Gate::define('viewSonar', function ($user) {
return $user->hasRole('admin') || $user->hasPermission('view-analytics');
});
}

Dashboard Access

The dashboard is available at /sonar and provides:

  • Event type distribution
  • Most active pages
  • Click and hover rates
  • User engagement metrics
  • Browser and device statistics
  • Screen size distribution
  • Detailed element interaction analysis

Using the Facade

The LaravelSonar facade provides various methods for analyzing your tracking data. Here's a comprehensive example:

class AnalyticsDashboardController extends Controller
{
    public function index()
    {
        return view('analytics.dashboard', [
            'eventsByType' => LaravelSonar::getEventsByType(now()->subDays(30)),
            'topPages' => LaravelSonar::getTopPages(5),
            'dailyEvents' => LaravelSonar::getEventTimeline(),
            'topClickedElements' => LaravelSonar::getTopEvents(5, 'click'),
            'engagement' => LaravelSonar::getUserEngagement(),
        ]);
    }
}

Available Analytics Methods

Basic Analytics

  • getEventsByType(DateTime $startDate = null, DateTime $endDate = null): Get event counts grouped by type
  • getTopLocations(int $limit = 10, DateTime $startDate = null): Get most active pages/routes
  • getEventTimeline(string $interval = '1 day', DateTime $startDate = null): Get event distribution over time
  • getTopEvents(int $limit = 10, string $type = null): Get most triggered events
  • getUserEngagement(): Get overall engagement metrics

Detailed Analytics

  • getElementStats(int $limit = 10): Get element-specific stats with conversion rates
  • getBrowserStats(): Get browser and device usage statistics
  • getScreenSizeStats(): Get screen size distribution
  • getMetadataStats(string $name): Get detailed metadata analysis for specific elements
  • getLocationStats(): Get detailed page interaction statistics

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Inspiration & Acknowledgments

Laravel Sonar was inspired by Pan, a lightweight and privacy-focused PHP product analytics library. While sharing similar core concepts for simple analytics tracking, Laravel Sonar extends the functionality with additional features including:

  • Rich metadata support for events
  • Built-in analytics dashboard UI
  • Advanced analytics reporting capabilities
  • Screen size and device tracking
  • Detailed user engagement metrics
  • React component integration
  • And more...

Credits

License

The MIT License (MIT). Please see License File for more information.

mafrasil/laravel-sonar 适用场景与选型建议

mafrasil/laravel-sonar 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 11 次下载、GitHub Stars 达 1, 最近一次更新时间为 2025 年 02 月 03 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「laravel」 「mafrasil」 「laravel-sonar」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 mafrasil/laravel-sonar 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 mafrasil/laravel-sonar 我们能提供哪些服务?
定制开发 / 二次开发

基于 mafrasil/laravel-sonar 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 11
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 12
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-02-03