Finite State Machine & persistence in Laravel
Asked Answered
D

1

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?

Dippold answered 7/4, 2014 at 11:4 Comment(2)
Please share your findings! :-)Atrium
How to start state machine with normal state? github.com/yohang/Finite/issues/114Grosbeak
A
3

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

PHP Files of interest:

Atrium answered 4/5, 2014 at 18:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.