Ahmed Chergaoui
Ahmed Chergaoui

Reputation: 103

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) :

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?

Upvotes: 6

Views: 3914

Answers (1)

menjaraz
menjaraz

Reputation: 7575

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

PHP Files of interest:

Upvotes: 3

Related Questions