6

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?

menjaraz
  • 7,551
  • 4
  • 41
  • 81
Ahmed Chergaoui
  • 103
  • 2
  • 6

1 Answers1

3

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

PHP Files of interest:

menjaraz
  • 7,551
  • 4
  • 41
  • 81