ondrej-vrto/laravel-visitors

Laravel 包,允许您将视图与 Eloquent 模型关联,并创建流量和统计。


README

Social Card of PHP Line Chart

一个允许您跟踪 Eloquent 模型流量的 Laravel 包。

Latest Version on Packagist Tests Total Downloads

序言

此工具根据欧洲 GDPR 指引,在不使用 cookies 或同意的情况下,启用基本用户活动监控。它在后台创建总体统计信息,这些统计信息生成时间较长,因此即使在大量数据中也能快速显示结果。

安装

您可以通过 composer 安装此包。

composer require ondrej-vrto/laravel-visitors

发布

php artisan vendor:publish --provider="OndrejVrto\Visitors\VisitorsServiceProvider"
# or separately
php artisan vendor:publish --tag=visitors-config
php artisan vendor:publish --tag=visitors-migrations
php artisan vendor:publish --tag=visitors-translations

基本使用访问计数器

将 "Visitable" 合同和 "InteractsWithVisits" 特性应用于模型

class Post extends Model implements Visitable
{
    use InteractsWithVisits;

    // Remove visits on delete model
    protected $removeDataOnDelete = true;

    // ...
}

在前端控制器中添加访问计数器。

public function show()
{
    $post = Post::find(5);
    $post->incrementVisit();

    $commercial = Commercial::find(100);
    $commercial->incrementVisit();

    return view('post.show', compact('post', 'commercial'));
}

基本使用显示统计信息

在仪表板中

public function dashboard()
{
    $topTenYearVisitsByPerson = Traffic::list()
        ->visitedByPersons()
        ->orderByLast365Days()
        ->withRelationship()
        ->limit(10)
        ->get();
    
    $sumarAllVisitFromWeb = Traffic::summary()
        ->visitedByPersons()
        ->inCategory(VisitorCategory::WEB)
        ->first();

    $sumarAllVisitFromApi = Traffic::summary()
        ->visitedByCrawlersAndPersons()
        ->inCategory(VisitorCategory::API)
        ->first();

    return view(
        'dashboard',
        compact('topTenYearVisitsByPerson', 'sumarAllVisit', '$sumarAllVisitFromApi')
    );
}

或在管理员控制器中的帖子列表。

public function index()
{
    $posts = Post::withTraffic()->paginate(10);

    return view('post.index', compact('posts'));
}

或在管理员控制器中的详细帖子。

public function show(Post $post)
{
    $visits = Traffic::single($post)
        ->inCategory(VisitorCategory::WEB)
        ->visitedByPersons()
        ->first();

    return view('post.show', compact('post', 'visits'));
}

自定义访问计数器

增量方法

// methods from model
$post->incrementVisit();
$post->incrementVisitForce();
// or with Facade
Visit::model($post)->increment();
// or with helper function
visit($post)->increment();

选项

// Check expiration time for ip address, model and category is is set
visit($post)->increment();
// Expiration time off
visit($post)->forceIncrement();

// With defining different categories for the record from Backed Enums
visit($post)->inCategory(VisitorCategory::WEB)->increment();

// Crawlers detection enabled/disabled. Rewrite config settings
visit($post)->withCrawlers()->increment();
visit($post)->withoutCrawlers()->increment();

// Rewrite default expires time
$expiresAt = now()->addHours(3); // `DateTimeInterface` instance
$expiresAt = 60; // minutes in Integer
visit($post)->expiresAt($expiresAt)->increment();

// dynamicaly create ip ignore list
visit($post)->addIpAddressToIgnoreList(['127.0.0.1', '147.7.54.789'])->increment();

手动添加的数据。

visit($post)
    ->fromIP('127.0.0.1')
    ->isCrawler()
    ->isPerson()
    ->inLanguage('Esperanto')
    ->fromBrowserAgent('custom browser agent string ....')
    ->fromOperatingSystem(OperatingSystem::WINDOWS)
    ->visitedAt(Carbon::now()->addMinute(5))
    ->increment();

修剪模型

注意: 在开始生成统计信息和流量之前,会自动运行修剪操作。

php artisan visitors:clean
// in App\Console\Kernel
$schedule->command('model:prune')->daily();
// OR
$schedule->command('model:prune', [
    '--model' => [VisitorsData::class, VisitorsExpires::class],
])->daily();
// OR
Artisan::call("visitors:clean");

生成流量数据

注意: 需要 Queue 服务。

php artisan visitors:fresh
// Manual in controller
Artisan::call("visitors:fresh");
// OR
(new TrafficGenerator())->run();
// Automatic in Scheduler (in App\Console\Kernel)
$schedule->command(VisitorsFreshCommand::class)->everyThreeHours();

调度器已包含在包中。如果将 schedule_generate_traffic_data_automaticaly 设置为 true,则无需设置其他内容。

查看流量数据

使用 SVG 预览图形,统计语言和操作系统。

多个模型的聚合数据

注意: 仅返回一条记录。

// summary global
$sumary = Traffic::summary()->first();    // with Facade
$sumary = traffic()->summary()->first();  // with helper function

// summary for all type models and all categories
$sumary = Traffic::summary()->visitedByPersons()->first();
$sumary = Traffic::summary()->visitedByCrawlers()->first();
$sumary = Traffic::summary()->visitedByCrawlersAndPersons()->first();

// summary for all type models and one category
$sumary = Traffic::summary()->inCategory(VisitorCategory::WEB)->first();

// summary for one type model and all categories
$sumary = Traffic::summary()->forModel(Post::class)->first();
$sumary = Traffic::summary()->forModel('App\Models\Post')->first();

// speciffic select
$sumary = Traffic::summary()
    ->forModel(Post::class)
    ->inCategory(VisitorCategory::WEB)
    ->visitedByCrawlersAndPersons()
    ->first();

特定模型的流量

注意: 仅返回一条记录。

$post = Post::find(1);

// Return model instance Traffic or null
$single = Traffic::single($post)->first();    // with Facade
$single = traffic()->single($post)->first();  // with helper function

// adds relationships to the Visitable Model
$single = Traffic::single($post)->withRelationship()->first();

其他选项类似于前一章中的统计信息

// summary for one model for all categories visited by persons
$single = Traffic::single($post)->visitedByPersons()->first();

// summary for one model for one category and all bots
$single = Traffic::single($post)->inCategory(VisitorCategory::WEB)->first();

// summary for one model for one category visited only persons
$single = Traffic::single($post)
    ->inCategory(VisitorCategory::WEB)
    ->visitedByCrawlersAndPersons()
    ->first();

最受欢迎的访问模型列表

注意: 返回模型实例的集合流量。

// Return Eloquent Builder
$traffic = Traffic::list();    // with Facade
$traffic = traffic()->list();  // with helper function

// Return collection, first model from collection or paginator
$traffic = Traffic::list()->get();
$traffic = Traffic::list()->first();
$traffic = Traffic::list()->paginate();

// adds relationships to the Visitable Model
$traffic = traffic()->list()->withRelationship()->get();

// only specific models type
$models = [VisitableModel::class, AnotherVisitableModel::class, "App\Models\Post"];
$traffic = Traffic::list($models)->get();

其他选项

$traffic = Traffic::list($models)
    ->inCategory(VisitorCategory::WEB)
    ->inCategories([VisitorCategory::WEB, VisitorCategory::API])
    ->forModel(Post::class)
    ->addModels([Example::class])
    ->orderByTotal()
    ->orderByLastDay()
    ->orderByLast7Days()
    ->orderByLast30Days()
    ->orderByLast365Days()
    ->orderBy('column_name', 'asc')
    ->visitedByPersons()
    ->visitedByCrawlers()
    ->visitedByCrawlersAndPersons()
    ->withRelationship()
    ->limit(10)
    ->get();   //->first();   //->paginate();

模型的关系作用域是可能的

将所有流量数据连接到 Visitable 模型

$post = Post::find($id)->withTraffic()->first();
// all scopes
$posts = Post::query()
    ->withTraffic()
    ->orderByTotal()
    ->orderByLastDay()
    ->orderByLast7Days()
    ->orderByLast30Days()
    ->orderByLast365Days()
    ->paginate();

获取最新流量生成过程的状态和附加数据

显示生成器的最后运行参数以及与当前数据的差异

$info = Traffic::info();

语言

枚举类 'OperatingSystem' 和 'VisitorCategory' 是可翻译的。

包配置

    /*
    / --------------------------------------------------------------------------
    / Eloquent settings
    / --------------------------------------------------------------------------
    /*
    / Here you can configure the table names in database.
    */

    'table_names' => [
        'info'    => 'visitors_info',
        'data'    => 'visitors_data',
        'expires' => 'visitors_expires',
        'traffic' => 'visitors_traffic',
    ],


    /*
    / --------------------------------------------------------------------------
    / Categories
    / --------------------------------------------------------------------------
    /
    / Use one of the options of the enum VisitCategory to set
    / the default category.
    /
    / Default: OndrejVrto\Visitors\Enums\VisitorCategory::UNDEFINED
    */

    'default_category' => OndrejVrto\Visitors\Enums\VisitorCategory::UNDEFINED,


    /*
    / --------------------------------------------------------------------------
    / Default expires time in minutes
    / --------------------------------------------------------------------------
    /
    / If you want set expiration time for ip adress and models in minutes.
    / Ignore this setting apply forceIncrement() method
    /
    / Default: 15
    */

    'expires_time_for_visit' => 15,


    /*
    / --------------------------------------------------------------------------
    / Ignore Bots and IP addresses
    / --------------------------------------------------------------------------
    /
    / If you want to ignore bots, you can specify that here. The default
    / service that determines if a visitor is a crawler is a package
    / by JayBizzle called CrawlerDetect.
    /
    / Default value: false
    */

    'storage_request_from_crawlers_and_bots' => false,


    /*
    / Ignore views of the following IP addresses.
    */

    'ignored_ip_addresses' => [
        // '127.0.0.1',
    ],


    /*
    / --------------------------------------------------------------------------
    / Statistics and traffic data
    / --------------------------------------------------------------------------
    /
    / The number of days after which traffic data will be deleted from today.
    / Warning: Older data will be permanently deleted.
    /
    / Value range  : 1 day - 36500 days
    / Default value: 730 (two years)
    */

    'number_days_traffic' => 730,


    /*
    / Create separate daily traffic graphs for used categories.
    /
    / Warning: Slows down data generation.
    / Default: false
    */

    'generate_traffic_for_categories' => false,


    /*
    / Create separate daily traffic graphs for crawlers and persons.
    /
    / Note   : If is set "storage_request_from_crawlers_and_bots" to true or apply withCrawlers() method.
    / Warning: Slows down data generation.
    / Default: false
    */

    'generate_traffic_for_crawlers_and_persons' => false,


    /*
    / Schedule the generation of traffic data and statistics within
    / the internal scheduler of this package. It will run every three hours.
    /
    / Note   : Equivalent to setting in the scheduler (in App\Console\Kernel)
    /          $schedule->command(VisitorsFreshCommand::class)->everyThreeHours();
    / Default: true
    */

    'schedule_generate_traffic_data_automaticaly' => true,


    /*
    / --------------------------------------------------------------------------
    / Line graphs in SVG
    / --------------------------------------------------------------------------
    /
    / Note:  https://github.com/OndrejVrto/php-linechart
    */

    'generate_graphs' => true,

    'graphs_properties' => [

        'maximum_value_lock' => null,
        'maximum_days'       => null,
        'order_reverse'      => false,
        'width_svg'          => 1000,
        'height_svg'         => 50,
        'stroke_width'       => 2,
        'colors'             => ['#4285F4', '#31ACF2', '#2BC9F4'],

    ],

测试

composer test

变更日志

有关最近更改的更多信息,请参阅 CHANGELOG

致谢

替代方案

许可证

MIT 许可证 (MIT)。有关更多信息,请参阅 许可证文件