PHPackages                             konsulting/fluent-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. konsulting/fluent-state-machine

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

konsulting/fluent-state-machine
===============================

1.0.2(3y ago)3305MITPHPPHP ^7.0 | ^8.0

Since Oct 3Pushed 3y ago2 watchersCompare

[ Source](https://github.com/konsulting/fluent-state-machine)[ Packagist](https://packagist.org/packages/konsulting/fluent-state-machine)[ RSS](/packages/konsulting-fluent-state-machine/feed)WikiDiscussions master Synced 4w ago

READMEChangelog (2)Dependencies (4)Versions (6)Used By (0)

Fluent State Machine
====================

[](#fluent-state-machine)

A simple fluent implementation of a state machine. If you've ever battled with trying to control and report state for an object in your php project - a state machine will help.

There are a few notable php state machine libraries around already - but didn't quite fit right, although we've used them in projects before. This is not an exhaustive list.

- [yohang/finite](https://github.com/yohang/Finite)
- [winzou/state-machine](https://github.com/winzou/state-machine)
- [definitely246/state-machine](https://github.com/definitely246/state-machine)
- [Symfony WorkFlow Component](https://symfony.com/doc/current/components/workflow.html) can be used as a State Machine.

Installation
------------

[](#installation)

`composer require konsulting/state-machine`

Simple Example
--------------

[](#simple-example)

We can construct a basic state machine easily, using a door as an example:

```
    use Konsulting\StateMachine\StateMachine;

    $door = new StateMachine(['closed', 'open'])
        ->addTransition('open')->from('closed')->to('open')
        ->addTransition('close')->from('open')->to('closed');
```

When constructing a StateMachine, the first state is assumed to be the default.

We can then try to transition the state machine to a new state:

```
    $door->transition('open'); // will complete successfully

    $door->transition('close'); // will throw a TransitionFailed Exception
```

We can also check if a transition is possible:

```
    $door->can('open'); // returns true

    $door->can('close'); // returns false
```

Real usage
----------

[](#real-usage)

In real usage, we will have a object (model) where the state machine is responsible for controlling the transitions that can be applied (and therefore controlling the models behaviour)

This can be accomplished two ways with this library.

1. We can attach a model to the state machine, and the state machine can manipulate the model. In very simple cases, this may be enough.
2. We can attach the state machine to a model, and the model's methods use the state machine to determine if it is able to proceed with an action.

### Real usage 1 - attach a model to the state machine

[](#real-usage-1---attach-a-model-to-the-state-machine)

As you will see, only the state machine retains the state information and we use it to control the flow in the script.

```
    use Konsulting\StateMachine\StateMachine;

    $simpleDoor = new SimpleDoor();

    $sm = new StateMachine(['closed', 'open'])
        ->setModel($state)
        ->addTransition('open')->from('closed')->to('open')
        ->addTransition('close')->from('open')->to('closed');

    $sm->transition('open');     // outputs opening
    echo $sm->getCurrentState(); // outputs open
    $sm->transition('close');    // outputs closing
    echo $sm->getCurrentState(); // outputs closed
```

```
    class SimpleDoor
    {
        public function open()
        {
            echo "opening";
        }

        public function close()
        {
            echo "closing";
        }
    }
```

*Side note:* This example makes use of automatic wiring to use a model method called the same name as the transition (in camelCase). We can also define a method specifically by passing a string, or any other [callable](http://php.net/manual/en/language.types.callable.php).

### Real usage 2 - attach the state machine to a model

[](#real-usage-2---attach-the-state-machine-to-a-model)

For this we extend the AttachableStateMachine which is set up to allow us to programmatically define the state machine, and accepts a model as its' constructor.

The end point is that we use the model in the natural manner we want to.

```
    $door = new Door('closed');

    $door->close(); // throws TransitionFailed Exception.

    $door->open();  // outputs "I am opening"
    $door->close(); // outputs "I am closing"
```

In the door class' methods we pass through a callback to be run as part of the transition. We are also able to pass through a callback to be run if the transition fails (instead of throwing an exception).

```
class Door
{
    public    $state;
    protected $stateMachine;

    public function __construct($state)
    {
        $this->state = $state;
        $this->stateMachine = new AttachedStateMachine($this);
    }

    public function open()
    {
        $this->stateMachine->transition('open', function () {
            echo "I am opening";
        });
    }

    public function close()
    {
        $this->stateMachine->transition('close', function () {
             echo "I am closing";
        });
    }
}
```

The AttachedStateMachine defines itself during construction. It grabs the current status from the model, and makes sure to stamp it back when setting the current status.

We also stop the auto wiring, so the state machine doesn't end up in an infinite loop trying to call it's calling method.

```
use Konsulting\StateMachine\AttachableStateMachine;
use Konsulting\StateMachine\StateMachine;
use Konsulting\StateMachine\TransitionFactory;
use Konsulting\StateMachine\Transitions;

class AttachedStateMachine extends AttachableStateMachine
{
    protected function define()
    {
        $transitionFactory = (new TransitionFactory)->useDefaultCall(false);
        $transitions = new Transitions($transitionFactory);

        $this->setTransitions($transitions)
            ->setStates(['closed', 'open'])
            ->setCurrentState($this->model->state ?? 'closed')
            ->addTransition('open')->from('closed')->to('open')
            ->addTransition('close')->from('open')->to('closed');
    }

    public function setCurrentState($state)
    {
        if ($this->model) {
            $this->model->state = $state;
        }

        return parent::setCurrentState($state);
    }
}
```

Contributing
------------

[](#contributing)

Contributions are welcome and will be fully credited. We will accept contributions by Pull Request.

Please:

- Use the PSR-2 Coding Standard
- Add tests, if you’re not sure how, please ask.
- Document changes in behaviour, including readme.md.

Testing
-------

[](#testing)

We use [PHPUnit](https://phpunit.de)

Run tests using PHPUnit: `vendor/bin/phpunit`

###  Health Score

33

—

LowBetter than 72% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity15

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity72

Established project with proven stability

 Bus Factor1

Top contributor holds 94.7% 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 ~967 days

Total

3

Last Release

1257d ago

PHP version history (2 changes)1.0.0PHP ^7.0

1.0.2PHP ^7.0 | ^8.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/4703657?v=4)[Konsulting](/maintainers/konsulting)[@konsulting](https://github.com/konsulting)

---

Top Contributors

[![Keoghan](https://avatars.githubusercontent.com/u/6714599?v=4)](https://github.com/Keoghan "Keoghan (18 commits)")[![rdarcy1](https://avatars.githubusercontent.com/u/15962421?v=4)](https://github.com/rdarcy1 "rdarcy1 (1 commits)")

---

Tags

fluentphpstate-machine

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/konsulting-fluent-state-machine/health.svg)

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

###  Alternatives

[matomo/matomo

Matomo is the leading Free/Libre open analytics platform

21.6k38.2k](/packages/matomo-matomo)[phpro/soap-client

A general purpose SoapClient library

8895.9M52](/packages/phpro-soap-client)[civicrm/civicrm-core

Open source constituent relationship management for non-profits, NGOs and advocacy organizations.

751284.3k37](/packages/civicrm-civicrm-core)[symfony/ai-platform

PHP library for interacting with AI platform provider.

521.2M216](/packages/symfony-ai-platform)[metamodels/core

MetaModels core

9956.1k68](/packages/metamodels-core)[verbb/shippy

A framework agnostic, multi-carrier shipping library for PHP.

1611.3k2](/packages/verbb-shippy)

PHPackages © 2026

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