Skip to content
Advertisement

PHP state machine framework

I doubt that is there any state machine framework like https://github.com/pluginaweek/state_machine for PHP.

I’ve had to define many if-else logical clauses, and I would like something to help make it more fun by just defining:

  1. Condition required to transition
  2. State after transition

Then this can be reused to check if conditions match or not, for example

JavaScript

I expect this line of code to implicitly check if the customer can transition or not. Or explicitly check by:

JavaScript

Thanks in advance, noomz

Advertisement

Answer

I don’t know a framework like this (which doesn’t mean it does not exist). But while not as feature packed as the linked framework, the State pattern is rather simple to implement. Consider this naive implementation below:

JavaScript

After you defined the states, you just have to apply them to your main object:

JavaScript

And then you can do

JavaScript

For reducing overly large if/else statements, this should be sufficient. Note that returning a new state instance on each transition is somewhat inefficient. Like I said, it’s a naive implementation to illustrate the point.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement