Eloquent State Machines is a package by Andrés Santibáñez that simplifies transitioning the states of Eloquent models:
During this weekend, I started working on a new package for @laravelphp to manage state machines for Eloquent models. Had so much fun and learned a ton in the process.
I've just tagged v1.0.0. Enjoy!https://t.co/9CrZ4azz3C
Feedback welcomed!
— Andrés Santibáñez (@asantibanez) December 7, 2020
Transitioning states is accomplished by defining the transition logic in a specific state machine. Here’s an example from the readme of a SalesOrder model:
1// 'pending', 'approved', 'declined' or 'processed' 2$salesOrder->status; 3// null, 'pending', 'completed' 4$salesOrder->fulfillment; 5 6// 7// Transition state examples 8// 9 10$salesOrder->status()->transitionTo('approved');11$salesOrder->fulfillment()->transitionTo('completed');12 13// Transition with custom properties14$salesOrder->status()->transitionTo('approved', [15 'comments' => 'Customer has available credit',16]);
Here are some examples of checking the transition history:
1$salesOrder->status()->was('approved');2$salesOrder->status()->timesWas('approved');3$salesOrder->status()->whenWas('approved');4$salesOrder->fulfillment()->snapshowWhen('completed');5$salesOrder->status()->history()->get();
Finally, here’s an example of how a model might consume this package:
1namespace App\Models; 2 3use App\StateMachines\SalesOrders\StatusStateMachine; 4use Asantibanez\LaravelEloquentStateMachines\Traits\HasStateMachines; 5use Illuminate\Database\Eloquent\Factories\HasFactory; 6use Illuminate\Database\Eloquent\Model; 7 8class SalesOrder extends Model 9{10 use HasFactory;11 use HasStateMachines;12 13 public $stateMachines = [14 'status' => StatusStateMachine::class,15 ];16}
Andrés has a demo application available to demonstrate how to use this package with Laravel. You can learn more about this package, get full installation instructions, and view the source code on GitHub.
0 comments:
Post a Comment
Thanks