PHPackages                             lesichkovm/php-state-machine - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. lesichkovm/php-state-machine

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

lesichkovm/php-state-machine
============================

State machine

v0.2.0(4y ago)044proprietaryPHP

Since Mar 26Pushed 4y ago2 watchersCompare

[ Source](https://github.com/lesichkovm/php-state-machine)[ Packagist](https://packagist.org/packages/lesichkovm/php-state-machine)[ Docs](http://github.com/lesichkovm/php-state-machine)[ RSS](/packages/lesichkovm-php-state-machine/feed)WikiDiscussions master Synced 1w ago

READMEChangelog (2)Dependencies (1)Versions (3)Used By (0)

PHP State Machine (PSM)
=======================

[](#php-state-machine-psm)

[![Tests Status](https://github.com/lesichkovm/php-state-machine/actions/workflows/php.yml/badge.svg?branch=master)](https://github.com/lesichkovm/php-state-machine/actions/workflows/php.yml)

The PHP State Machine (PSM) is a state machine that is easy to understand and implement.

The PSM consists of a single file that is easy to drag and drop into your project.

Configuration
-------------

[](#configuration)

```
$config = [
    'states' => array(
        'checkout',
        'pending',
        'confirmed',
        'cancelled'
    ),
    'transitions' => array(
        'create' => array(
            'from' => array('checkout'),
            'to' => 'pending'
        ),
        'confirm' => array(
            'from' => array('checkout', 'pending'),
            'to' => 'confirmed'
        ),
        'cancel' => array(
            'from' => array('confirmed'),
            'to' => 'cancelled'
        )
    ),
];
$stateMachine = new \App\Helpers\StateMachine;
$stateMachine->setConfig($config);
```

Get Current State
-----------------

[](#get-current-state)

PSM will give you the current state

```
var_dump($stateMachine->getState());
```

Check if Transition can be Applied
----------------------------------

[](#check-if-transition-can-be-applied)

Before applying a transition, check whether it can be applied

```
// Return true, we can apply this transition
var_dump($stateMachine->canTransition('create'));
var_dump($stateMachine->applyTransition('create'));
```

Get Possible Transitions
------------------------

[](#get-possible-transitions)

PSM can easily show the possible transitions from the current state

```
// All possible transitions for pending state are just "confirm"
var_dump($stateMachine->getPossibleTransitions());
```

Get History
-----------

[](#get-history)

PSM keeps track of the history.

```
var_dump($stateMachine->getHistory());
```

Persisting State
----------------

[](#persisting-state)

The PSM makes it easy to persist the state to a file or database, and restore later.

### Saving PSM to File

[](#saving-psm-to-file)

```
$stateMachine = new StateMachine();
file_put_contents('sm.json', $stateMachine->toString());
```

### Restoring PSM from File

[](#restoring-psm-from-file)

```
$stateMachine = new StateMachine();
$stateMachine->fromString(json_decode(file_get_contents('sm.json'), true));
```

Examples
--------

[](#examples)

### 1. Smart Lamp

[](#1-smart-lamp)

This is an example of a lamp that can be switched on and off. It is smart as can only only switch on during the night to save energy. The check if it can be turned on is done via a validator

```
class SmartLamp extends StateMachine
{
    const STATE_OFF = "off";
    const STATE_ON = "on";

    const TRANSITION_TO_ON = "to_on";
    const TRANSITION_TO_OFF = "to_off";

    public $dayOrNight = "day";

    function __construct()
    {
        //parent::__construct();
        $config = [
            "states" => [
                self::STATE_OFF,
                self::STATE_ON,
            ],
            "transitions" => array(
                self::TRANSITION_TO_ON => array(
                    "from" => array(self::STATE_OFF),
                    "to" => self::STATE_ON,
                    "validators" => [
                        [$this, "validateIsNight"],
                    ]
                ),
                self::TRANSITION_TO_OFF => array(
                    "from" => array(self::STATE_ON),
                    "to" => self::STATE_OFF
                ),
            ),
        ];
        $this->setConfig($config);
    }

    function validateIsNight()
    {
        return $this->dayOrNight == "night";
    }
}
```

How to use:

```
$lamp = new SmartLamp;

$lamp->dayOrNight = "day"; // We tell the lamp its day

// This will not execute, as its currently day time
if ($lamp->canTransition(SmartLamp::TRANSITION_TO_ON)) {
    $lamp->applyTransition(SmartLamp::TRANSITION_TO_ON);
}

$lamp->dayOrNight = "night"; // Now we tell the lamp its night

// This will execute, as its currently night time
if ($lamp->canTransition(SmartLamp::TRANSITION_TO_ON)) {
    $lamp->applyTransition(SmartLamp::TRANSITION_TO_ON);
}
```

###  Health Score

21

—

LowBetter than 17% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity8

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity41

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

1605d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7744963?v=4)[Milan Lesichkov](/maintainers/lesichkovm)[@lesichkovm](https://github.com/lesichkovm)

---

Top Contributors

[![lesichkovm](https://avatars.githubusercontent.com/u/7744963?v=4)](https://github.com/lesichkovm "lesichkovm (26 commits)")

---

Tags

phpstatemachinelesichkov

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/lesichkovm-php-state-machine/health.svg)

```
[![Health](https://phpackages.com/badges/lesichkovm-php-state-machine/health.svg)](https://phpackages.com/packages/lesichkovm-php-state-machine)
```

###  Alternatives

[eftec/statemachineone

A state Machine library for business processes

1154.0k](/packages/eftec-statemachineone)[rolfvreijdenberger/izzum-statemachine

A superior statemachine library php &gt;= 5.3. Integrates with your domain models perfectly.

7426.1k](/packages/rolfvreijdenberger-izzum-statemachine)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
