定制 jooservices/laravel-events 二次开发

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

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

jooservices/laravel-events

Composer 安装命令:

composer require jooservices/laravel-events

包简介

EventSourcing and EventLog for Laravel with MongoDB storage

README 文档

README

CI OpenSSF Scorecard PHP Version License: MIT Packagist Version

Lightweight Event Sourcing and Event Log persistence for Laravel with MongoDB storage. Store domain event payloads by aggregate and/or model change audit trails (prev/changed/diff) via Laravel's native event dispatcher.

Package name: jooservices/laravel-events

Introduction

This package adds two persistence features on top of Laravel's event system:

  1. Event Sourcing — Events implementing EventSourcingInterface are stored in a stored_events MongoDB collection (payload, aggregate id, metadata, user, time). Use for aggregate history, replay-oriented records, or audit by aggregate.
  2. Event Log — Events implementing LoggableModelInterface are stored in an event_logs collection with previous/changed state and a per-field diff. Use for audit trails and compliance.

You dispatch events as usual; package subscribers persist them to MongoDB. No custom bus or queue required.

Scope

Use this package when you need a reusable Laravel-standard base library for persisting event records or audit logs.

This package does not:

  • replace Laravel's event dispatcher
  • provide a projection/read-model framework
  • provide a business analytics or reporting layer
  • provide dashboards, projections, or analytics/reporting workflows
  • provide AI agents, AI data fetching, or an AI runtime

When to Use

Need Use
Persist domain events by aggregate for historical inspection or replay-aware workflows Event Sourcing
Persist model/entity changes with previous/current values and field diff Event Log
Need both domain history and field-level audit Use both, with separate focused events
Need dashboards, projections, analytics, or AI retrieval Build that in the application layer

Quick Start

Install

composer require jooservices/laravel-events

Publish config (optional)

php artisan vendor:publish --tag=laravel-events-config

Environment

MONGODB_URI=mongodb://127.0.0.1:27017
MONGODB_DATABASE=your_db
EVENTS_EVENTSOURCING_ENABLED=true
EVENTS_EVENT_LOG_ENABLED=true

Ensure a mongodb connection exists in config/database.php (see mongodb/laravel-mongodb).

Indexes

php artisan events:install-indexes

Basic Usage

Event Sourcing

Implement EventSourcingInterface and dispatch:

use JOOservices\LaravelEvents\EventSourcing\Contracts\EventSourcingInterface;

class OrderCreated implements EventSourcingInterface
{
    public function __construct(public string $orderId, public array $items) {}

    public function payload(): array
    {
        return ['order_id' => $this->orderId, 'items' => $this->items];
    }

    public function aggregateId(): ?string
    {
        return $this->orderId;
    }
}

event(new OrderCreated('ORD-001', [['sku' => 'X', 'qty' => 2]]));

Events are stored in the stored_events collection. Optional: occurredAt(): ?\Carbon\CarbonInterface, metadata(): array. Use the HasEventSourcingDefaults trait to implement only payload() and aggregateId().

Recommended metadata keys include request_id, correlation_id, causation_id, source, channel, reason_code, schema_version, event_version, event_category, and optional tenant_id. The EventMetadata helper exposes constants and small factory methods for those conventions.

Use event_category for a lightweight event type convention when you need broad categories such as domain, integration, audit, or system without introducing a full event taxonomy framework.

Event Log (Audit)

Implement LoggableModelInterface (and optionally HasLogAction) and dispatch with prev/changed state. Use the DefaultsToUpdatedAction trait when the action is always updated:

use JOOservices\LaravelEvents\EventLog\Concerns\DefaultsToUpdatedAction;
use JOOservices\LaravelEvents\EventLog\Contracts\LoggableModelInterface;
use JOOservices\LaravelEvents\EventLog\Contracts\HasLogAction;

class OrderUpdated implements LoggableModelInterface, HasLogAction
{
    use DefaultsToUpdatedAction;

    public function __construct(public Order $model, public array $prev) {}

    public function getLoggableType(): string { return $this->model->getMorphClass(); }
    public function getLoggableId(): string { return (string) $this->model->getKey(); }
    public function getPrev(): array { return $this->prev; }
    public function getChanged(): array { return $this->model->getAttributes(); }
}

Changes are stored in event_logs with a computed diff. Query by entity_type + entity_id.

Recommended action names are available from JOOservices\LaravelEvents\EventLog\EventLogAction: created, updated, deleted, restored, status_changed, corrected, synchronized, and imported.

Querying

use JOOservices\LaravelEvents\Query\EventLogQueryService;
use JOOservices\LaravelEvents\Query\StoredEventQueryService;

$events = app(StoredEventQueryService::class)->byAggregateId('ORD-001');
$domainEvents = app(StoredEventQueryService::class)->byEventCategory('domain');
$audit = app(EventLogQueryService::class)->byEntity('orders', 'ORD-001');

Query services return typed package data records and intentionally stay small. Build dashboards, projections, and reporting in your application.

JOOservices\... is the canonical package namespace in 1.2.0. The legacy JooServices\... namespace remains available for backward compatibility.

Redaction

Recursive redaction is enabled by default for common secret keys:

'redaction' => [
    'enabled' => true,
    'keys' => ['password', 'token', 'authorization'],
    'replacement' => '[REDACTED]',
],

This masks stored event payload/metadata and event log prev, changed, diff, and meta. It is defensive masking, not a replacement for avoiding secrets in dispatched events.

Retention

Optional MongoDB TTL indexes are configured with:

EVENTS_STORED_EVENTS_RETENTION_DAYS=
EVENTS_EVENT_LOGS_RETENTION_DAYS=365

Run php artisan events:install-indexes after changing retention settings. MongoDB TTL deletion is asynchronous.

Bulk Records

use JOOservices\LaravelEvents\Data\StoredEventData;
use JOOservices\LaravelEvents\EventService;

app(EventService::class)->recordManyStoredEvents([
    new StoredEventData('OrderImported', ['order_id' => 'ORD-001'], 'ORD-001'),
]);

Bulk APIs normalize and redact each record before MongoDB batch insert.

Documentation

Full documentation is in the ./docs folder:

Document Description
docs/README.md Documentation index
Architecture Design, data flow, diagrams
Code structure Package layout and namespaces
Installation Requirements and setup
Configuration Config and context provider
Decision Guide Event Sourcing vs Event Log
Event Sourcing Stored events and aggregates
Event Log Audit trail and diff
Metadata Metadata keys, versioning, corrections
Operations Indexes, query patterns, retention, production safety
AI Integration Optional app-layer AI export examples
Development Composer commands, CI, release, and contributor workflow
Samples Complete code examples
API Reference EventService, interfaces, commands

Testing & Linting

composer test
composer test:coverage
composer lint       # Pint, PHPCS, PHPStan
composer lint:all   # lint + PHPMD + PHP-CS-Fixer
composer lint:fix   # Pint fix + PHP-CS-Fixer fix
composer check      # lint:all + test
composer ci         # lint:all + test:coverage

Git Hooks

Composer installs Git hooks automatically on dependency install and update:

composer install
composer update

The hooks are managed by CaptainHook and enforce:

  • commit-msg: Conventional Commits, for example fix: Correct event metadata merge
  • pre-commit: PHP syntax linting, staged secret scanning with gitleaks, Pint, PHPCS, PHPStan, PHPMD, and PHP-CS-Fixer
  • pre-push: gitleaks history scan when available, then composer test

If hooks need to be reinstalled manually:

vendor/bin/captainhook install --force --skip-existing

Install gitleaks locally to pass the pre-commit secret scan:

brew install gitleaks

AI Contributor Support

AI contributor guidance is intentionally documentation-only:

The package does not include AI runtime code, AI data fetching, authorization, redaction, or tool execution.

DTO-Style Records

The package uses small typed data records for normalized stored event and audit log data. It follows jooservices/dto as a maturity baseline for repository quality and docs structure, without depending on DTO domain internals.

GitHub Actions

Configured workflows:

  • CI: Composer metadata validation, Composer audit, Pint, PHPCS, PHPStan, PHPMD, PHP-CS-Fixer, PHPUnit coverage with a MongoDB service, a 95% minimum statement coverage gate, guarded Codecov upload, guarded SonarQube Cloud analysis, and non-blocking dependency review for pull requests
  • Release: validate version tags, create GitHub releases, and trigger Packagist updates when Packagist secrets are configured
  • PR Labeler: apply labels based on changed files
  • Semantic PR Title: enforce Conventional Commit-style PR titles
  • OpenSSF Scorecard: publish security posture results as SARIF
  • Secret Scanning: run Gitleaks on pushes, pull requests, and manual dispatches

Coverage is archived as a workflow artifact. Codecov and SonarQube Cloud are optional and only run when repository secrets are configured, so README badges do not claim those services as mandatory package support.

License

This project is licensed under the MIT License.

jooservices/laravel-events 适用场景与选型建议

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

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

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-03-09