PHPackages                             pear/fsm - 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. pear/fsm

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

pear/fsm
========

Finite State Machine

355.0k12[1 issues](https://github.com/pear/FSM/issues)PHP

Since Mar 19Pushed 5y ago3 watchersCompare

[ Source](https://github.com/pear/FSM)[ Packagist](https://packagist.org/packages/pear/fsm)[ RSS](/packages/pear-fsm/feed)WikiDiscussions master Synced 2d ago

READMEChangelogDependenciesVersions (1)Used By (0)

The FSM Package
===============

[](#the-fsm-package)

User Documentation
------------------

[](#user-documentation)

Author:Jon PariseContact:Contents

- [1 About the FSM Package](#about-the-fsm-package)
- [2 Building a Finite State Machine](#building-a-finite-state-machine)
    - [2.1 Creating a New FSM Object](#creating-a-new-fsm-object)
    - [2.2 Defining Transitions](#defining-transitions)
    - [2.3 Setting Default Transitions](#setting-default-transitions)
- [3 Plotting a State Machine](#plotting-a-state-machine)
- [4 Development and Support](#development-and-support)
    - [4.1 Reporting Problems and Suggestions](#reporting-problems-and-suggestions)
    - [4.2 Coming Soon](#coming-soon)

[1 About the FSM Package](#id1)
-------------------------------

[](#1about-the-fsm-package)

The [FSM Package](http://pear.php.net/package/FSM) implements a [Finite State Machine](http://wikipedia.org/wiki/Finite_state_machine). In addition to maintaining state, this FSM also manages a user-defined payload, therefore effectively making the machine a [Pushdown Automaton](http://wikipedia.org/wiki/Push-down_automata) (a finite state machine with memory).

This code is based largely on Noah Spurrier's excellent [FSM Python class](http://www.noah.org/python/FSM/).

[2 Building a Finite State Machine](#id2)
-----------------------------------------

[](#2building-a-finite-state-machine)

The first step in building a Finite State Machine involves listing the finite set of states. Then, all of the permissible transitions between these states must be defined. A symbol and an optional callback function are associated with each transition. The input processing routine will attempt to match its current symbol against the list of registered transitions. If a transition from the current state using that symbol is found, the machine will move to the new state specified by the transition and, if one has been specified, the associated callback function will be invoked.

### [2.1 Creating a New FSM Object](#id3)

[](#21creating-a-new-fsm-object)

Start by including the FSM package in your script:

```
require 'FSM.php';
```

When constructing a new FSM object, you must specify the machine's initial state and provide a payload variable. The payload will be passed to all of the callback functions, supplying them with state information without (ab)using global variables.

In this example, we pass an array representing a stack as the payload. The machine's initial state is set to `START`.

```
$stack = array();
$fsm = new FSM('START', $stack);
```

### [2.2 Defining Transitions](#id4)

[](#22defining-transitions)

We'll need to define some transitions in order to make our machine useful. Let's assume our machine has two additional states: `MIDDLE` and `END`. Here's how we would define transitions to move us from `START` to `MIDDLE`and from `MIDDLE` to `END`:

```
function FirstCallback($symbol, &$payload, $currentState, $nextState)
{
    echo "First Transition\n";
}

function SecondCallback($symbol, &$payload, $currentState, $nextState)
{
    echo "Second Transition\n";
}

$fsm->addTransition('FIRST', 'START', 'MIDDLE', 'FirstCallback');
$fsm->addTransition('SECOND', 'MIDDLE', 'END', 'SecondCallback');
```

Our machine is now aware of three states (`START`, `MIDDLE`, and `END`) and two symbols (`FIRST` and `SECOND`). Two transitions (`START` to `MIDDLE` and `MIDDLE` to `END`) have been defined and associated with callbacks. The following code will process the symbols `FIRST` and `SECOND` and move us from our initial state (`START`) through the `MIDDLE` state to the `END` state.

```
$fsm->process('FIRST');
$fsm->process('SECOND');
```

The processing routine will invoke our two callbacks along the way, as well, resulting in the following being printed:

```
First Transition
Second Transition
```

### [2.3 Setting Default Transitions](#id5)

[](#23setting-default-transitions)

Now we'll set up a default transition. This transition will be used whenever the processing routine cannot find a better match for the current state and symbol. For our example, we'll consider this an error and print a warning for the user.

```
function ErrorCallback($symbol, &$payload, $currentState, $nextState)
{
    echo "This symbol does not compute: $symbol\n";
}

$fsm->setDefaultTransition('START', 'ErrorCallback');
```

Now let's process our symbols in an unexcepted order:

```
$fsm->process('SECOND');
$fsm->process('FIRST');
```

Because the `SECOND` transition doesn't specify `START` as its initial state, the default transition will be used and the error callback will be invoked. The `FIRST` transition will work as expected, however, because the machine will still be in the `START` state.

[3 Plotting a State Machine](#id6)
----------------------------------

[](#3plotting-a-state-machine)

The FSM package optionally supports the ability to plot a machine's states with the help of the [Image\_GraphViz](http://pear.php.net/package/Image_GraphViz) package. Doing so is as simple as creating a new `FSM_GraphViz` object using an existing state machine instance and then exporting the graph.

```
require_once 'FSM/GraphViz.php';
$converter = new FSM_GraphViz($fsm);
$graph = $converter->export();
```

The resulting graph object is an `Image_GraphViz` instance. To export the graph as an image, use the `image()` method:

```
$graph->image('png');
```

This will produce an image similar to the following:

[![Example State Machine Plot](https://camo.githubusercontent.com/d5dfd43eed20aaa7bdf89be63cc8d74aff68ef0be21d603fa40b1d8189c4db75/68747470733a2f2f7261772e6769746875622e636f6d2f706561722f46534d2f6d61737465722f646f63732f677261706876697a2e706e67)](https://camo.githubusercontent.com/d5dfd43eed20aaa7bdf89be63cc8d74aff68ef0be21d603fa40b1d8189c4db75/68747470733a2f2f7261772e6769746875622e636f6d2f706561722f46534d2f6d61737465722f646f63732f677261706876697a2e706e67)

Consult the [Image\_GraphViz documentation](http://pear.php.net/package/Image_GraphViz/docs) for additional usage information.

[4 Development and Support](#id7)
---------------------------------

[](#4development-and-support)

### [4.1 Reporting Problems and Suggestions](#id8)

[](#41reporting-problems-and-suggestions)

If you run into a problem or would like to make a suggestion, please use the [PEAR Bug Tracker](http://pear.php.net/bugs/). Feel free to contact me directly for other issues, but please try to use the bug tracker whenever possible so that others in the community will benefit from your feedback and my responses.

- [Open Bugs](http://pear.php.net/package/FSM/bugs)
- [Report a New Bug](http://pear.php.net/bugs/report.php?package=FSM)

### [4.2 Coming Soon](#id9)

[](#42coming-soon)

This section contains a list of "todo" items that will hopefully be addressed in future releases.

- *No items at this time.*

If you have feature suggestions, please submit them using the [PEAR Bug Tracker](http://pear.php.net/bugs/).

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance19

Infrequent updates — may be unmaintained

Popularity31

Limited adoption so far

Community18

Small or concentrated contributor base

Maturity30

Early-stage or recently created project

 Bus Factor1

Top contributor holds 87.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.

### Community

Maintainers

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

---

Top Contributors

[![jparise](https://avatars.githubusercontent.com/u/10311?v=4)](https://github.com/jparise "jparise (64 commits)")[![CloCkWeRX](https://avatars.githubusercontent.com/u/365751?v=4)](https://github.com/CloCkWeRX "CloCkWeRX (3 commits)")[![ftwbzhao](https://avatars.githubusercontent.com/u/492682?v=4)](https://github.com/ftwbzhao "ftwbzhao (2 commits)")[![till](https://avatars.githubusercontent.com/u/27003?v=4)](https://github.com/till "till (2 commits)")[![mj](https://avatars.githubusercontent.com/u/5277?v=4)](https://github.com/mj "mj (1 commits)")[![urg](https://avatars.githubusercontent.com/u/2316449?v=4)](https://github.com/urg "urg (1 commits)")

### Embed Badge

![Health badge](/badges/pear-fsm/health.svg)

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

PHPackages © 2026

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