PHPackages                             mouadziani/xstate - 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. mouadziani/xstate

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

mouadziani/xstate
=================

State machine library to play with any complex behavior of your PHP objects

1.0.1(3y ago)866.7k↓50%5[3 PRs](https://github.com/mouadziani/xstate/pulls)MITPHPPHP ^8.0CI passing

Since Jun 11Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/mouadziani/xstate)[ Packagist](https://packagist.org/packages/mouadziani/xstate)[ Docs](https://github.com/mouadziani/xstate) Fund[ GitHub Sponsors](https://github.com/mouadziani)[ RSS](/packages/mouadziani-xstate/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (2)Versions (7)Used By (0)

 [![xstate php logo](/art/logo.png)](/art/logo.png)

XState - State Machine for PHP
------------------------------

[](#xstate---state-machine-for-php)

XState is a [state machine](https://statecharts.dev/what-is-a-state-machine.html) library to play with any complex behavior of your PHP objects (inspired by [xstate.js](https://github.com/statelyai/xstate))

### Installation

[](#installation)

The recommended way to install Xstate is through [Composer](https://getcomposer.org/)

```
composer require mouadziani/xstate
```

### Define state machine workflow

[](#define-state-machine-workflow)

 [![Video state machine diagram](/art/diagram.png)](/art/diagram.png)

Let's say we want to define a state machine workflow for a video object, generally a video may have 3 states (playing, stopped, paused),

as a first step you have to create a new object from `StateMachine` class

```
use \Mouadziani\XState\StateMachine;

$video = StateMachine::make();
```

Then you have to define the allowed states as well as the default state

```
$video
    ->defaultState('stopped')
    ->states(['playing', 'stopped', 'paused']);
```

And finally the transitions

```
use \Mouadziani\XState\Transition;

$video->transitions([
    new Transition('PLAY', ['stopped', 'paused'], 'playing'),
    new Transition('STOP', 'playing', 'stopped'),
    new Transition('PAUSE', 'playing', 'paused'),
    new Transition('RESUME', 'paused', 'playing'),
]);
```

The `Transition` class expect 3 required params:

- **Trigger**: As a name of the transition which will be used to trigger a specific transition *(should be unique)*
- **From**: Expect a string for a single / or array for multiple initial allowed states
- **To**: Expect string which is the next target state *(should match one of the defined allowed states)*

#### Guards (optional)

[](#guards-optional)

You can either define a guard callback for a specific transition using `guard` method, which must return a bool. If a guard returns false, the transition cannot be performed.

```
use \Mouadziani\XState\Transition;

$video->transitions([
    (new Transition('PLAY', ['stopped', 'paused'], 'playing'))
        ->guard(function ($from, $to) {
            return true;
        })
]);
```

### 💡 You can define the whole workflow using a single statement:

[](#-you-can-define-the-whole-workflow-using-a-single-statement)

```
$video = StateMachine::make()
    ->defaultState('playing')
    ->states(['playing', 'stopped', 'paused'])
    ->transitions([
        new Transition('PLAY', ['stopped', 'paused'], 'playing'),
        new Transition('STOP', 'playing', 'stopped'),
        new Transition('PAUSE', 'playing', 'paused'),
    ]);
```

### Work with states &amp; transitions

[](#work-with-states--transitions)

#### Trigger transition

[](#trigger-transition)

There are two ways to trigger a specific defined transition

1- Using `transitionTo` method and specify the name of the transition as an argument

```
$video->transitionTo('PLAY');
```

2- Or just calling the name of the transition from your machine object as a method

```
$video->play();
```

Occasionally triggering a transition may throw an exception if the target transition is not defined /or not allowed:

```
use \Mouadziani\XState\Exceptions;

try {
    $video->transitionTo('RESUME');
} catch (Exceptions\TransitionNotDefinedException $ex) {
    // the target transition is not defined
} catch (Exceptions\TransitionNotAllowedException $ex) {
    // the target transition is not allowed
}
```

#### Get the current state

[](#get-the-current-state)

```
echo $video->currentState(); // playing
```

#### Get the allowed transitions

[](#get-the-allowed-transitions)

```
$video->allowedTransitions(); // ['STOP', 'PAUSE']
```

#### Adding in-demand transition

[](#adding-in-demand-transition)

```
$video->addTransition(new Transition('TURN_OFF', 'playing', 'stopped'));
```

Upcoming features
-----------------

[](#upcoming-features)

- Add the ability to define guard for a specific transition
- Define/handle hooks before/after triggering transition

Testing
-------

[](#testing)

```
composer test
```

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Mouad Ziani](https://github.com/mouadziani)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

featured\_repository

###  Health Score

43

—

FairBetter than 91% of packages

Maintenance51

Moderate activity, may be stable

Popularity36

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 72.9% 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 ~36 days

Total

2

Last Release

1401d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/d86641a10bf69b9d9820c6a5cdee8ae57f913d7406f6bb6ed8890d8cc6c15b65?d=identicon)[MouadZIANI](/maintainers/MouadZIANI)

---

Top Contributors

[![mouadziani](https://avatars.githubusercontent.com/u/29683939?v=4)](https://github.com/mouadziani "mouadziani (51 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (9 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (9 commits)")[![ayyoub-afwallah](https://avatars.githubusercontent.com/u/64936175?v=4)](https://github.com/ayyoub-afwallah "ayyoub-afwallah (1 commits)")

---

Tags

state-machinexstatesagamouadziani

###  Code Quality

TestsPest

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/mouadziani-xstate/health.svg)

```
[![Health](https://phpackages.com/badges/mouadziani-xstate/health.svg)](https://phpackages.com/packages/mouadziani-xstate)
```

###  Alternatives

[metabor/statemachine

Statemachine in PHP 5.3

103150.7k2](/packages/metabor-statemachine)[tarfin-labs/event-machine

Event-driven state machines for Laravel with event sourcing, type-safe context, and full audit trail.

188.5k](/packages/tarfin-labs-event-machine)[ringierimu/state-workflow

Laravel State Workflow provide tools for defining and managing workflows and activities with ease.

3251.1k](/packages/ringierimu-state-workflow)[shrink0r/workflux

Finite state machine for php.

375.6k1](/packages/shrink0r-workflux)[phpmentors/stagehand-fsm

A finite state machine

361.1k](/packages/phpmentors-stagehand-fsm)

PHPackages © 2026

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