create-state

Generate a State Pattern implementation for PHP 8.4: create a state machine consisting of a context object, a state interface, and concrete state classes to enable runtime behavior changes. Include corresponding unit tests.

Last repository push
GitHub Stars
109
Forks
26
Issues / PRs
1

Installation

Review the source and dependencies with a prompt. A package is available to download.

Install with an AI assistant

Copy the prompt so your assistant can review the pinned revision and dependencies first.

View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "create-state" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-b37fcdffd9d3a265536650ec992d5944e707f7e10901a83f09d783a85f591d8b. Verify the upstream source and version against https://github.com/dykyi-roman/awesome-claude-code before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.

Source and setup

github.com

Setup guidance pending

See the original source for supported tools, dependencies, and permissions.

Installation test pending

Generate a State Pattern implementation for PHP 8.4: create a state machine consisting of a context object, a state interface, and concrete state classes to enable runtime behavior changes. Include corresponding unit tests.

0 Downloads

Introduction source: third_party · dykyi-roman · 0.0.1 Reference

SkillPi interpretation

Tasks
Generates State pattern for PHP 8.4. Creates state machines with context, state interface, and concrete states for behavior changes. Includes unit tests.
Audience
| Scenario | Example | |----------|---------| | Object behavior varies by state | Order (pending, paid, shipped) | | Many conditionals based on state | Document workflow | | State-specific transitions | Subscription lifecycle | | Finite state machines | Payment processing |
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: create-state
description: Generates State pattern for PHP 8.4. Creates state machines with context, state interface, and concrete states for behavior changes. Includes unit tests.

State Pattern Generator

Creates State pattern infrastructure for objects that change behavior based on internal state.

When to Use

Scenario Example
Object behavior varies by state Order (pending, paid, shipped)
Many conditionals based on state Document workflow
State-specific transitions Subscription lifecycle
Finite state machines Payment processing

Component Characteristics

StateInterface

  • Defines available actions
  • Returns new state after transition
  • Encapsulates state-specific behavior

Context

  • Holds current state
  • Delegates actions to state
  • Manages state transitions

Concrete States

  • Implement behavior for each state
  • Handle valid/invalid transitions
  • Return appropriate next state

Generation Process

Step 1: Analyze State Machine

Determine:

  • All possible states
  • Actions/transitions between states
  • Which actions are valid per state
  • Terminal states (no outgoing transitions)

Step 2: Generate State Components

Path: src/Domain/{BoundedContext}/State/

  1. {Name}StateInterface.php — State contract with all actions
  2. Abstract{Name}State.php — Base class with default (invalid) implementations
  3. {StateName}State.php — Concrete state for each state (PendingState, PaidState, etc.)
  4. {Name}StateFactory.php — Factory for reconstitution from storage

Path: src/Domain/{BoundedContext}/Exception/

  1. InvalidStateTransitionException.php — Exception for invalid transitions

Step 3: Update Entity

Path: src/Domain/{BoundedContext}/Entity/

Update entity to use state pattern with delegation methods.

Step 4: Generate Tests

Path: tests/Unit/Domain/{BoundedContext}/State/

  1. {StateName}StateTest.php — Test each concrete state
  2. {Entity}StateTransitionTest.php — Test full state machine

File Placement

Component Path
State Interface src/Domain/{BoundedContext}/State/
Concrete States src/Domain/{BoundedContext}/State/
State Factory src/Domain/{BoundedContext}/State/
Entity with State src/Domain/{BoundedContext}/Entity/
Exception src/Domain/{BoundedContext}/Exception/
Unit Tests tests/Unit/Domain/{BoundedContext}/State/

Naming Conventions

Component Pattern Example
Interface {Name}StateInterface OrderStateInterface
Abstract State Abstract{Name}State AbstractOrderState
Concrete State {StateName}State PendingState, PaidState
Factory {Name}StateFactory OrderStateFactory
Exception InvalidStateTransitionException InvalidStateTransitionException
Test {ClassName}Test PendingStateTest

Quick Template Reference

State Interface

interface {Name}StateInterface
{
    public function getName(): string;
    public function {action1}({Context} $context): self;
    public function {action2}({Context} $context): self;
    public function canTransitionTo(self $state): bool;
    /** @return array<string> */
    public function allowedTransitions(): array;
}

Abstract State

abstract readonly class Abstract{Name}State implements {Name}StateInterface
{
    public function {action1}({Context} $context): {Name}StateInterface
    {
        throw InvalidStateTransitionException::actionNotAllowed('{action1}', $this->getName());
    }

    public function canTransitionTo({Name}StateInterface $state): bool
    {
        return in_array($state->getName(), $this->allowedTransitions(), true);
    }
}

Concrete State

final readonly class {StateName}State extends Abstract{Name}State
{
    public function getName(): string
    {
        return '{state_name}';
    }

    public function {action1}({Context} $context): {Name}StateInterface
    {
        $context->recordEvent(new {Event}($context->id()));
        return new {NextState}State();
    }

    public function allowedTransitions(): array
    {
        return ['{next_state_1}', '{next_state_2}'];
    }
}

State Factory

final class {Name}StateFactory
{
    public static function fromName(string $name): {Name}StateInterface
    {
        return match ($name) {
            'pending' => new PendingState(),
            'confirmed' => new ConfirmedState(),
            default => throw new \InvalidArgumentException("Unknown state: $name"),
        };
    }
}

Usage Example

// Entity with state
$order = new Order($id, $customerId, $items);
$order->confirm();  // Pending -> Confirmed
$order->pay();      // Confirmed -> Paid
$order->ship();     // Paid -> Shipped
$order->deliver();  // Shipped -> Delivered

// Check state
if ($order->isInState('delivered')) {
    // ...
}

// Reconstitute from storage
$state = OrderStateFactory::fromName($row['state']);
$order = new Order($id, $customerId, $items, $state);

State Diagram Template

┌──────────┐  action1   ┌──────────┐  action2   ┌──────────┐
│  State1  │───────────▶│  State2  │───────────▶│  State3  │
└────┬─────┘            └────┬─────┘            └──────────┘
     │                       │
     │ cancel                │ cancel
     │                       │
     ▼                       ▼
┌──────────┐            ┌──────────┐
│Cancelled │            │Cancelled │
└──────────┘            └──────────┘

Anti-patterns to Avoid

Anti-pattern Problem Solution
Mutable States Shared state pollution Make states readonly
God State One state handles all Split into specific states
Missing Transitions Silent failures Throw on invalid action
State in Entity Mixed concerns Extract to State classes
No Factory Hard to reconstitute Add StateFactory

References

For complete PHP templates and examples, see:

  • references/templates.md — State interface, abstract, concrete templates
  • references/examples.md — Order state machine example and tests

Current listing version

0.0.1

Verify the source revision ↗

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value88/100

Highlights

  • 提供 PHP 8.4 状态模式的完整生成方案,包含上下文、状态接口、具体状态、异常处理、工厂模式及单元测试
  • 适用于对象行为随状态变化的常见场景(如订单、文档工作流等),具有明确的实用价值和广泛适用性
Trigger Precision92/100

Highlights

  • description 明确描述了功能(为 PHP 8.4 生成状态模式,包含状态机、单元测试),触发词清晰,覆盖典型使用场景,边界明确
Structure and Standards95/100

Highlights

  • 文档结构完整,包含 When to Use、Component Characteristics、Generation Process(分步骤)、File Placement、Naming Conventions、Quick Template Reference、Usage Example、State Diagram、Anti-patterns、References 等章节
  • 步骤清晰,有出口条件,含端到端示例,frontmatter 完整,单文件未超 500 行
Execution Reliability90/100

Highlights

  • 提供了完整的代码模板(接口、抽象类、具体状态、工厂、异常)、文件路径规范、命名约定、测试结构
  • 工具来源明确(PHP 标准语法),参数正确,覆盖主要异常(InvalidStateTransitionException),不可逆操作(状态转换)有确认机制(canTransitionTo)
Evidence Verifiability (mean of the first four)91/100

The arithmetic mean of the first four original scores, rounded to a whole number.

Static text checks

100 / 100 · skillpi-20261123-no-r3-v1

No current rules matched the text.

This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.

Permissions and checks before use

Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.

These common operations were not identified in the main document. This does not mean no permissions or risks exist.

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.