Cook php
Published in

Cook php

Creating a State Machine using PHP

What is a State Machine?.

A State Machine also called Automata (yes, like the game) is a concept to design and organize process and workflows by considering the current “state” of a job, the change of states and, in the possible, to (ahem), automate the process.

I explain. For example, let’s say that I want to buy milk, my job has the next states:

  • Initial State
  • Driving to buy milk
  • Picking the milk
  • Paying for the milk
  • Drive back home.

Where is it used?.

Everywhere. In most if not all business process that requires at least two “states”. For example, delivery companies, purchase operation, hiring process and such.

Why I need a State Machine?

But, let’s go back to the example of the milk. Why I need to create a State Machine where the process is from A-Z?.
It is because thing happens, error, mistakes or problems could arise.
For example, the case of buy milk, what if I don’t bring money, or the store is closed, or there is not milk, or if I have trouble driving (is snowing).
So, the states are now as follow:

  • Initial State
  • Driving to buy milk
  • Cancel driving.
  • Picking the milk
  • Paying for the milk
  • Unable to purchase
  • Drive back home.

It is even possible to add more states, but they are the basic. It is also possible to shrink and uses fewer states, such as simple “cancel state.”

How I can automate the process?

And now, how I can automate the process, or more specifically, how I can automate the change of states?.
Each change of state is called TRANSITION. A transition happens because of some values, programming function or time and it is what the system uses to automate the process.
For example of milk, I will use the next values (or fields).

  • milk=0 there is not milk, milk=1 I have milk
  • money = money in my pocket.
  • price = price of the milk
  • stock_milk = number of milks on the store
  • store_open =0 closed, =1 open
  • gas = gas of my car.

So, the states and transitions are as follow

  • Initial State ➡️ Driving to buy milk
    When? when milk=0 and gas>0
  • Driving to buy milk ➡️ Cancel Driving (it is the end of the job)
    When? gas=0
  • Driving to buy milk ➡️ Picking the Milk
    When? store_open=1 and stock_milk>0
  • Driving to buy milk ➡️ Unable to purchase
    When? store_open=0 or stock_milk=0
  • Picking the Milk ➡️ Paying for the milk (it also increase milk +1)
    When? money>=price
  • Picking the Milk ➡️ Unable to purchase
    When? money<price
  • Unable to purchase ➡️ Drive back home. (end of the process)
    When? always
  • Paying for the milk ➡️ Drive back home. (end of the process)
    When? always

PHP code

In our example (less than 100 lines of code), we are omiting some key parts of our project. Let’s say that we want to use a robot to do this task, this robot will require sensors and many other algoritms but the concept of State Machine is still valid but it requires integration with other system/application.

Now, let’s program this one.

First, our exercise use Composer for load the library and we use this library (it’s free for personal and commercial products):

You could install this library using Composer

composer require eftec/statemachineone

Also, we also need a Mysql Database and MysqlI connector. It is the standard pipeline of PHP.

And let’s create a new project: We need to program a single file one.

First part

First, we initialized the code, we added the library and we create a new instance of StateMachineOne();

Second, our variables

Now, we define our variables such as state and initial values.

So, Are we using the same states defined conceptually?. Yes and it is important. It is really easy to miss a step, or to omit a vital operation, so the code must be as clean as possible, because it could be modified or altered.

Third, connection to the database

Now, we connected to the database (mysql). We must set the database (localhost in the example), user (root), password(abc.123) and the database/schema to use (statemachinedb). It also creates two tables called buymilk_jobs and buymilk_logs automatically. You could create it manually if you want to. The library uses a database as an optional component.

Fourth, defining the new transitions

Now, we define the transition between states.

What is the meaning of the string ‘when ….’ ?. It is the state machine language, it is basic but it does it’s job. However, it requires space for every command (it is for optimization), for example: money<price is wrong, while money < price (see spaces) is right.

Fifth, And finally we group it all in together.

What does the magic of Automata is the function checkAllJobs(). Also, the library has a visual interface so where we could test the jobs. The UI is optional because every job could be programmed via code.

Testing using the UI

If the configuration is correct, then our page should show the new screen.

Now, let’s create a new Job. Let’s start with the initial fields milk=0, money=999 and gas=10 and click on the Create a new job button

Now, the job was created and jumped from the state Driving(1) to the state Buy Milk(2)

Job #11 2018–12–09 19:06:11.232900 [INFO]: state changed from 1 to 2 changed (it is a log message thanks to the debug option)

Let’s set the next values, store_open=1 and stock_milk=1 and click on the button Set field values (it will set new values and will test all the conditions)

So the job jumped from Driving to Buy Milk(2) -> Picking the Milk (4), and it sets the value of milk to 1.

Also, the job jumped from Picking the Milk (4) -> Paying for the Milk (5) in the same step. Why? It is because the job fulfill it’s conditions.

Job #11 2018–12–09 19:09:06.502700 [INFO]: state changed from 2 to 4 changed
setting milk = 1
Job #11 2018–12–09 19:09:06.514600 [INFO]: state changed from 4 to 5 changed

Now, let’s click in the button Refresh (it will test all jobs again) and the job will change state from Paying for the Milk (5) -> Drive Back Home (7) and the job will stop, completing the cycle.

Job #11 2018–12–09 19:12:41.435900 [INFO]: state changed from 5 to 7 stopped

Comments and suggest

Was this article helpful?

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store