本文へ移動
cccskills
無料GitHub で公開

acc-event-sourcing-knowledge

Event Sourcing knowledge base. Provides patterns, antipatterns, and PHP-specific guidelines for Event Sourcing architecture audits.

インストール方法を見る

含まれるファイル(1)

  • SKILL.md6.3 KB

SKILL.md(原文)

インストールする前に、エージェントに与えられる指示の中身を確認できます。

Event Sourcing Knowledge Base

Quick reference for Event Sourcing architecture patterns and PHP implementation guidelines.

Core Principles

Event Sourcing Fundamentals

Traditional Storage:          Event Sourcing:
┌─────────────────┐           ┌─────────────────┐
│  Current State  │           │  Event Stream   │
│  ─────────────  │           │  ─────────────  │
│  Order #123     │           │  1. OrderCreated│
│  Status: Paid   │           │  2. ItemAdded   │
│  Total: $150    │           │  3. ItemAdded   │
└─────────────────┘           │  4. OrderPaid   │
       ↓                      └────────┬────────┘
  Direct update                        │
                                       ▼
                              ┌─────────────────┐
                              │  Current State  │
                              │  (Rebuilt from  │
                              │   events)       │
                              └─────────────────┘

Rule: Store events, derive state. Never modify events.

Key Concepts

ConceptDescription
EventImmutable record of something that happened
Event StoreAppend-only storage for events
Event StreamOrdered sequence of events for one aggregate
AggregateConsistency boundary, rebuilt from events
ProjectionRead model built by processing events
SnapshotCached aggregate state for performance

Quick Checklists

Event Checklist

  • Named in past tense (OrderCreated, ItemAdded)
  • Immutable (readonly class)
  • Contains all data needed to apply change
  • Has metadata (timestamp, causation, correlation IDs)
  • No business logic
  • Versioned for schema evolution

Aggregate Checklist

  • State rebuilt from events only
  • apply*() methods modify state from events
  • record*() methods create and apply events
  • No direct state modification
  • Returns uncommitted events for persistence

Event Store Checklist

  • Append-only (no updates, no deletes)
  • Ordered within stream
  • Supports optimistic concurrency
  • Events never modified
  • Stream position tracking

Projection Checklist

  • Idempotent event handlers
  • Can be rebuilt from scratch
  • Handles event ordering
  • Tracks processed position

Common Violations Quick Reference

ViolationWhere to LookSeverity
Mutable eventEvent with settersCritical
Direct state mutationAggregate bypassing eventsCritical
Missing event dataEvent without full state infoCritical
Event with logicEvent doing calculationsWarning
Non-idempotent projectionProjection with side effectsWarning
Missing metadataEvent without timestamp/IDsWarning

PHP 8.5 Event Sourcing Patterns

Domain Event

final readonly class OrderConfirmedEvent
{
    public function __construct(
        public string $orderId,
        public int $totalCents,
        public string $currency,
        public DateTimeImmutable $confirmedAt,
        public EventMetadata $metadata
    ) {}
}

final readonly class EventMetadata
{
    public function __construct(
        public string $eventId,
        public DateTimeImmutable $occurredAt,
        public ?string $causationId = null,
        public ?string $correlationId = null,
        public int $version = 1
    ) {}
}

Event-Sourced Aggregate

final class Order extends EventSourcedAggregate
{
    private OrderStatus $status;
    private Money $total;

    public static function create(OrderId $id, CustomerId $customerId): self
    {
        $order = new self($id);
        $order->recordThat(new OrderCreatedEvent(
            orderId: $id->value,
            customerId: $customerId->value,
            createdAt: new DateTimeImmutable()
        ));
        return $order;
    }

    public function confirm(): void
    {
        if ($this->status !== OrderStatus::Draft) {
            throw new InvalidStateException();
        }
        $this->recordThat(new OrderConfirmedEvent(
            orderId: $this->id->value,
            totalCents: $this->total->cents(),
            currency: $this->total->currency(),
            confirmedAt: new DateTimeImmutable()
        ));
    }

    protected function applyOrderCreatedEvent(OrderCreatedEvent $event): void
    {
        $this->status = OrderStatus::Draft;
        $this->total = Money::zero('USD');
    }

    protected function applyOrderConfirmedEvent(OrderConfirmedEvent $event): void
    {
        $this->status = OrderStatus::Confirmed;
    }
}

Projection

final class OrderListProjection
{
    public function __construct(
        private Connection $connection
    ) {}

    public function applyOrderCreatedEvent(OrderCreatedEvent $event): void
    {
        $this->connection->insert('order_list', [
            'id' => $event->orderId,
            'customer_id' => $event->customerId,
            'status' => 'draft',
            'created_at' => $event->createdAt->format('Y-m-d H:i:s'),
        ]);
    }

    public function applyOrderConfirmedEvent(OrderConfirmedEvent $event): void
    {
        $this->connection->update('order_list', [
            'status' => 'confirmed',
            'total_cents' => $event->totalCents,
            'confirmed_at' => $event->confirmedAt->format('Y-m-d H:i:s'),
        ], ['id' => $event->orderId]);
    }
}

References

For detailed information, load these reference files:

  • references/event-store-patterns.md — Event persistence, streams, concurrency
  • references/projection-patterns.md — Read model projections
  • references/snapshot-patterns.md — Performance optimization with snapshots
  • references/versioning-patterns.md — Event schema evolution
  • references/antipatterns.md — Common violations with detection patterns

レビュー

まだレビューはありません。使ってみた感想をお寄せください。

同じリポジトリのスキル

概要と使いどころ

Master backend architectures, REST API design, microservices, and server-side development across multiple languages. Use this as a central index to access specialized sub-skills.

日本語の概要は準備中です。原文の説明を表示しています。

MikeCheng1208/BattleTree22026年7月22日 更新

在每次回复中使用固定前缀并列出本次实际参考的指令/文件,便于校验是否遵循上下文与规则。

日本語の概要は準備中です。原文の説明を表示しています。

MikeCheng1208/BattleTree22026年7月22日 更新

Automate 21risk tasks via Rube MCP (Composio). Always search tools first for current schemas.

日本語の概要は準備中です。原文の説明を表示しています。

MikeCheng1208/BattleTree22026年7月22日 更新

Automate 2chat tasks via Rube MCP (Composio). Always search tools first for current schemas.

日本語の概要は準備中です。原文の説明を表示しています。

MikeCheng1208/BattleTree22026年7月22日 更新

Arquitecto de Soluciones Principal y Consultor Tecnológico de Andru.ia. Diagnostica y traza la hoja de ruta óptima para proyectos de IA en español.

日本語の概要は準備中です。原文の説明を表示しています。

MikeCheng1208/BattleTree22026年7月22日 更新

[00] META. Orchestrate skills into dynamic chains for complex tasks. Analyzes the task, discovers available skills, builds an optimal chain, explains why each skill is needed, and executes step-by-step with user confirmation. Use for any complex task requiring multiple thinking/research/analysis steps. Triggers on "plan this", "how to approach", "what's the strategy", "build a plan", or any multi-step problem requiring skill orchestration.

日本語の概要は準備中です。原文の説明を表示しています。

MikeCheng1208/BattleTree22026年7月22日 更新

MikeCheng1208 のスキルをすべて見る

このスキルの問題を報告する