BehavioralPHPverifiedVerified

State Pattern in PHP

Allows an object to alter its behavior when its internal state changes, appearing as if the object has changed its class.

How to Implement the State Pattern in PHP

1Step 1: Define the state interface

interface State
{
    public function handle(Context $context): void;
    public function getName(): string;
}

2Step 2: Implement the context that delegates to the current state

class Context
{
    private State $state;

    public function __construct(State $initialState)
    {
        $this->state = $initialState;
    }

    public function setState(State $state): void
    {
        echo "Transitioning to: {$state->getName()}\n";
        $this->state = $state;
    }

    public function getState(): State { return $this->state; }

    public function request(): void
    {
        $this->state->handle($this);
    }
}

3Step 3: Implement concrete states with transitions

class IdleState implements State
{
    public function handle(Context $context): void
    {
        echo "Idle: starting processing...\n";
        $context->setState(new ProcessingState());
    }

    public function getName(): string { return 'Idle'; }
}

class ProcessingState implements State
{
    public function handle(Context $context): void
    {
        echo "Processing: work complete\n";
        $context->setState(new DoneState());
    }

    public function getName(): string { return 'Processing'; }
}

class DoneState implements State
{
    public function handle(Context $context): void
    {
        echo "Done: resetting...\n";
        $context->setState(new IdleState());
    }

    public function getName(): string { return 'Done'; }
}

// Usage
$context = new Context(new IdleState());
$context->request(); // Idle -> Processing
$context->request(); // Processing -> Done
$context->request(); // Done -> Idle

State Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

State Pattern in the Real World

Think of a traffic light. The light itself (context) doesn't change its wiring, but its active state—red, yellow, or green—completely determines what drivers should do. Each color has its own rules, and the light transitions through states on a timer. Adding a flashing-yellow state only requires defining that state's rules, not rewiring the entire light.