Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finite State Machine & persistence in Laravel

I'm wondering if Laravel has some built-in state machine mechanism? And if not, what's the best way to use this excellent library called Finite (https://github.com/yohang/Finite).

Here's what I have (use case : a job board) :

  • User creates an offer (initial state: created)
  • User previews the offer (state: draft)
  • User published the offer (final state: published)

To start, I made my model "stateful":

use Finite\StatefulInterface;
class Offer extends Eloquent implements StatefulInterface {

Then in my offers controller's store action:

$stateMachine = new StateMachine();
$stateMachine->addState(new State('created', StateInterface::TYPE_INITIAL));
$stateMachine->addState('draft');
$stateMachine->addState(new State('published', StateInterface::TYPE_FINAL));

$stateMachine->addTransition('preview', 'created', 'draft');
$stateMachine->addTransition('publish', 'draft', 'published');

$stateMachine->setObject($offer);
$stateMachine->initialize();

From what I understand, when a user previews an offer (for example), I should be calling:

$stateMachine->apply('preview').

My question is:

How do I keep track of all the states and transitions across my app? Do I store states in my Offer model? Do I create additional tables?

like image 888
Ahmed Chergaoui Avatar asked Apr 07 '14 11:04

Ahmed Chergaoui


People also ask

What is finite state machine with example?

A system where particular inputs cause particular changes in state can be represented using finite state machines. This example describes the various states of a turnstile. Inserting a coin into a turnstile will unlock it, and after the turnstile has been pushed, it locks again.

What is a finite state machine used for?

Introduction. A Finite State Machine, or FSM, is a computation model that can be used to simulate sequential logic, or, in other words, to represent and control execution flow. Finite State Machines can be used to model problems in many fields, including mathematics, artificial intelligence, games or linguistics.

What is a finite state machine in simple words?

Finite state machine (FSM) is a term used by programmers, mathematicians, engineers and other professionals to describe a mathematical model for any system that has a limited number of conditional states of being.

What is a state in a finite state machine?

A state machine reads a set of inputs and changes to a different state based on those inputs. A state is a description of the status of a system waiting to execute a transition. A transition is a set of actions to execute when a condition is fulfilled or an event received.


1 Answers

Please head to this gist: FiniteAuditTrail Trait: Such a good starting point for your request!

PHP Files of interest:

  • MyStatefulModel.php
  • MyStatefulModelStateTransition.php
  • Usage.php
like image 52
menjaraz Avatar answered Oct 14 '22 10:10

menjaraz