Skip to content
acc-create-state logo

State Pattern Generator

acc-create-state

Generates State pattern for PHP 8.5. Creates state machines with context, state interface, and concrete states for behavior changes. Includes unit tests.

SKILL.md

Full skill instructions

State Pattern Generator

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

When to Use

ScenarioExample
Object behavior varies by stateOrder (pending, paid, shipped)
Many conditionals based on stateDocument workflow
State-specific transitionsSubscription lifecycle
Finite state machinesPayment 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

ComponentPath
State Interfacesrc/​Domain/​{BoundedContext}/​State/
Concrete Statessrc/​Domain/​{BoundedContext}/​State/
State Factorysrc/​Domain/​{BoundedContext}/​State/
Entity with Statesrc/​Domain/​{BoundedContext}/​Entity/
Exceptionsrc/​Domain/​{BoundedContext}/​Exception/
Unit Teststests/​Unit/​Domain/​{BoundedContext}/​State/

Naming Conventions

ComponentPatternExample
Interface{Name}StateInterfaceOrderStateInterface
Abstract StateAbstract{Name}StateAbstractOrderState
Concrete State{StateName}StatePendingState, PaidState
Factory{Name}StateFactoryOrderStateFactory
ExceptionInvalidStateTransitionExceptionInvalidStateTransitionException
Test{ClassName}TestPendingStateTest

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-patternProblemSolution
Mutable StatesShared state pollutionMake states readonly
God StateOne state handles allSplit into specific states
Missing TransitionsSilent failuresThrow on invalid action
State in EntityMixed concernsExtract to State classes
No FactoryHard to reconstituteAdd 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

More DevOps & CI/CD skills

Project scaffolding, deployment configuration, and CI/CD setup for Google ADK agents.

6K 472.6K
View

Set up tracing, logging, and monitoring for deployed ADK agents across Cloud Trace, BigQuery, and third-party platforms.

6K 472.6K
View

Enterprise Azure infrastructure architect generating Bicep or Terraform from workload descriptions.

1.5K 454.3K
View
azure-kubernetes logo
DevOps & CI/CD

azure-kubernetes

Plan and configure production-ready Azure Kubernetes Service clusters with Day-0 and Day-1 best practices.

1.5K 447.1K
View

Raw mechanical interfaces fusing Swiss typographic print with military terminal aesthetics. Rigid grids, extreme type scale contrast, utilitarian color, analog degradation effects. For data-heavy dashboards, portfolios, or editorial sites that need to feel like declassified blueprints.

92.7K 354.9K
View
just-scrape logo
DevOps & CI/CD

just-scrape

Web search, scraping, extraction, crawling, and monitoring via ScrapeGraph AI CLI.

69 245K
View

Skill for working with Firebase Hosting (Classic). Use this when you want to deploy static web apps, Single Page Apps (SPAs), or simple microservices. Do NOT use for Firebase App Hosting.

462 159.7K
View

Deploy and manage web apps with Firebase App Hosting. Use this skill when deploying Next.js/Angular apps with backends.

462 159.1K
View
deploy-to-vercel logo
DevOps & CI/CD

deploy-to-vercel

Deploy applications and websites to Vercel. Use when the user requests deployment actions like "deploy my app", "deploy and give me the link", "push this live", or "create a preview deployment".

31.9K 146.6K
View
programmatic-seo logo
DevOps & CI/CD

programmatic-seo

Build SEO-optimized pages at scale using templates, data, and proven playbook patterns.

53.3K 140.1K
View

Design and build isolated, reusable Convex backend components with clear boundaries and app-facing wrappers.

63 123.5K
View

Deploy and manage projects on Vercel using token-based authentication. Use when working with Vercel CLI using access tokens rather than interactive login — e.g. "deploy to vercel", "set up vercel", "add environment variables to vercel".

31.9K 116.1K
View

Coding & apps AI tools

Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View
I
Coding & apps

Imagica

Build a no-code AI app in minutes.

Freemium
View
E
Coding & apps

Emergent.sh

An IDE for code migration from legacy to modern frameworks through coding agents.

Freemium
View
Wonder Dynamics logo
Coding & apps

Wonder Dynamics

Automate CGI animation in live-action scenes

Paid
View
M
Coding & apps

Mixo

Launch a website in seconds with AI.

Paid
View
AI Code Convert logo
Coding & apps

AI Code Convert

Streamline Your Coding Experience with AI Code Helper

Free
View