定制 aaronfrancis/eventable 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

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

aaronfrancis/eventable

Composer 安装命令:

composer require aaronfrancis/eventable

包简介

A Laravel package for tracking events on Eloquent models using polymorphic relationships

README 文档

README

Latest Version on Packagist Tests Total Downloads PHP Version License

A Laravel package for tracking events on Eloquent models with polymorphic relationships, backed enums, and query helpers for both individual event records and parent models.

Eventable stores both a registered enum alias in type_class and the enum backing value in type. That keeps overlapping enum values safe across multiple event enums and lets you rename enum classes without breaking historical data.

Highlights:

  • Works with int-backed and string-backed enums
  • Stores array payloads and exact scalar JSON values
  • Lets you query models by event history
  • Supports pruning by age, count, or both
  • Tested in CI on SQLite, MySQL 8, PostgreSQL 17, and PostgreSQL 18
// Add the trait to your User model
class User extends Model
{
    use HasEvents;
}

// Record events
$user->addEvent(UserEvent::LoggedIn);
$user->addEvent(UserEvent::SubscriptionStarted, ['plan' => 'pro']);

// Query by events
User::whereEventHasntHappened(UserEvent::EmailVerified)->get(); // Unverified users
User::whereLatestEventIs(UserEvent::Churned)->get();            // Churned users
User::whereEventHasHappenedAtLeast(UserEvent::Purchase, 5)->get(); // VIP customers

Installation

composer require aaronfrancis/eventable

Publish the config and migration:

php artisan vendor:publish --tag=eventable-config
php artisan vendor:publish --tag=eventable-migrations
php artisan migrate

Quick Start

1. Add the trait to your models

use AaronFrancis\Eventable\Concerns\HasEvents;

class User extends Model
{
    use HasEvents;
}

2. Create a backed enum for your event types

enum UserEvent: int
{
    case LoggedIn = 1;
    case EmailVerified = 2;
    case SubscriptionStarted = 3;
    case Churned = 4;
    case Purchase = 5;
    case PageViewed = 6;
    case PasswordResetRequested = 7;
}

The published migration uses a string column for type, so int-backed and string-backed enums both work out of the box. If you customize the migration to use an integer column, string-backed enums will no longer fit.

3. Register your enum in config/eventable.php

'event_types' => [
    'user' => App\Enums\UserEvent::class,
],

This registration is required. It enables:

  • Multiple enums without value collisions, such as UserEvent::Created = 1 and OrderEvent::Created = 1
  • Alias-aware queries when you pass a BackedEnum to ofType()
  • Refactoring enum class names without breaking stored records

4. Review morph key and morph map setup

The published migration uses morphs('eventable'), so it follows Laravel's default morph key type. If your app uses UUIDs or ULIDs for polymorphic keys, call Schema::morphUsingUuids() or Schema::morphUsingUlids() before running the migration.

Since Eventable uses polymorphic relationships, it is also a good idea to use Laravel's enforced morph map for your own models:

// In AppServiceProvider::boot()
use Illuminate\Database\Eloquent\Relations\Relation;

Relation::enforceMorphMap([
    'user' => \App\Models\User::class,
    'order' => \App\Models\Order::class,
]);

Eventable separately registers its own Event model in Laravel's morph map when eventable.register_morph_map is enabled.

Recording Events

$user->addEvent(UserEvent::LoggedIn);

$user->addEvent(UserEvent::Purchase, [
    'order_id' => 123,
    'total' => 99.99,
]);

$user->addEvent(UserEvent::PasswordResetRequested, false);

The second argument can be an array or any JSON-serializable scalar value. Exact scalar matching works for values like false, 0, '0', and ''.

Helper Methods

// Check if an event exists
$user->hasEvent(UserEvent::EmailVerified); // true or false

// Get the most recent event
$user->latestEvent(); // or filter by type
$user->latestEvent(UserEvent::Purchase);

// Get the first event
$user->firstEvent(UserEvent::LoggedIn);

// Count events
$user->eventCount(); // all events
$user->eventCount(UserEvent::LoggedIn); // by type

latestEvent() and whereLatestEventIs() use the same definition of "latest": newest created_at, with id as the tie-breaker. Those latest-event queries also resolve through your configured Event model, so custom global scopes stay in effect.

Querying a Model's Events

// Get all events for a model
$user->events;

// Filter by the enum alias and backing value
$user->events()->ofType(UserEvent::LoggedIn)->get();

// Filter by raw backing values when you also provide the enum alias
$user->events()->ofTypeClass('user')->ofType([1, 5])->get();

// Filter by data
$user->events()->whereData(['order_id' => 123])->get();
$user->events()->whereData(false)->get();

// Time-based queries
$user->events()->happenedAfter(now()->subDays(7))->get();
$user->events()->happenedBefore(now()->subMonth())->get();
$user->events()->happenedInTheLast(7, Unit::Day)->get();
$user->events()->happenedInTheLast(3, Unit::Hour)->get();
$user->events()->happenedToday()->get();
$user->events()->happenedThisWeek()->get();
$user->events()->happenedThisMonth()->get();

// With explicit timezone (defaults to app timezone)
$user->events()->happenedToday('America/Chicago')->get();

Raw values only filter the type column. If multiple enums can share the same backing values, pair raw values with ofTypeClass() or use an enum case directly.

Querying Models by Event Criteria

// Users who made a purchase over $100 in the last 7 days
User::whereHas('events', function ($query) {
    $query->ofType(UserEvent::Purchase)
        ->where('data->total', '>', 100)
        ->happenedAfter(now()->subDays(7));
})->get();

// Users who logged in today
User::whereHas('events', function ($query) {
    $query->ofType(UserEvent::LoggedIn)->happenedToday();
})->get();

// Users who viewed a specific page
User::whereHas('events', function ($query) {
    $query->ofType(UserEvent::PageViewed)
        ->whereData(['page' => '/pricing']);
})->get();

Querying Models by Events

// Find users who have logged in
User::whereEventHasHappened(UserEvent::LoggedIn)->get();

// Find users who haven't verified their email
User::whereEventHasntHappened(UserEvent::EmailVerified)->get();

// With specific data
User::whereEventHasHappened(UserEvent::Purchase, ['total' => 99.99])->get();

// With advanced Laravel query constraints on the matching events
User::whereEventHasHappened(UserEvent::Purchase, function ($events) {
    $events->where('data->total', '>', 99);
})->get();

// Count-based queries
User::whereEventHasHappenedTimes(UserEvent::LoggedIn, 3)->get(); // exactly 3 times
User::whereEventHasHappenedAtLeast(UserEvent::Purchase, 5)->get(); // at least 5 times

// Find by latest event
User::whereLatestEventIs(UserEvent::SubscriptionStarted)->get();

Pruning Old Events

Implement PruneableEvent on your registered enums to configure retention policies:

use AaronFrancis\Eventable\Contracts\PruneableEvent;
use AaronFrancis\Eventable\Prune;
use AaronFrancis\Eventable\PruneConfig;

enum UserEvent: int implements PruneableEvent
{
    case LoggedIn = 1;
    case EmailVerified = 2;
    // ... other cases ...
    case PageViewed = 6;

    public function prune(): PruneConfig|Prune|null
    {
        return match ($this) {
            // Keep only the last 5 login events per user
            self::LoggedIn => Prune::keep(5),

            // Delete page views older than 30 days
            self::PageViewed => Prune::before(now()->subDays(30)),

            default => null, // Don't prune
        };
    }
}

If you prefer, you can still return new PruneConfig(...) directly.

Run the prune command:

# Preview what will be deleted
php artisan eventable:prune --dry-run

# Actually prune
php artisan eventable:prune

Schedule it in your routes/console.php or kernel:

Schedule::command('eventable:prune')->daily();

PruneConfig must define at least one retention rule: before, keep, or both. Prune is a fluent builder for producing that config. When pruning by keep, Eventable keeps the newest rows by created_at desc, id desc. If varyOnData is enabled, rows are partitioned by model and canonicalized JSON payload before the keep limit is applied, so equivalent JSON objects are grouped together across supported drivers.

Custom Event Models

You can extend the default Event model:

<?php

namespace App\Models;

use AaronFrancis\Eventable\Models\Event as BaseEvent;

class Event extends BaseEvent
{
    // Your customizations
}

Then update the config:

'model' => App\Models\Event::class,

Relationships, direct Event queries, and the prune command all resolve through the configured model class.

Docs

License

MIT

aaronfrancis/eventable 适用场景与选型建议

aaronfrancis/eventable 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 0 次下载、GitHub Stars 达 4, 最近一次更新时间为 2025 年 12 月 28 日, 在 PHP 生态内属于活跃度较高的组件。

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

围绕 aaronfrancis/eventable 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-12-28