ilvalerione / statemachine
带有 Laravel/Eloquent 集成的状态机
1.2.0
2019-05-31 10:45 UTC
Requires
- php: >=7.1.0
- illuminate/support: 5.*
- symfony/property-access: ^4.0
Requires (Dev)
- orchestra/testbench: ~3.0
This package is auto-updated.
Last update: 2024-08-29 05:22:36 UTC
README
- 作者: Valerio Barbera - support@logengine.dev
- 作者网站: www.logengine.dev
基于 Laravel 的应用程序的状态机。
安装
composer require ilvalerione/statemachine
配置
php artisan vendor:publish --provider="Aventure\StateMachine\ServiceProvider"
此命令将在您的 config
目录中发布一个新的配置文件,列出您想要在应用程序中使用的所有状态图。
默认的配置文件附带了一个完整的图示例。
Eloquent 模型集成
将 HasStateMachine
特性添加到您想要管理其状态的对象的 Eloquent 模型中
class Order extends Model { use HasStateMachine; ...
将状态机配置分配给模型
class Order extends Model { use HasStateMachine; /** * StateMachine configuration * * @return array */ protected function stateMachineConfig() : array { // This is the name of the graph in the "state-machine.php" config file return [ 'graph' => 'order', ]; } }
默认状态
使用 Eloquent 的 $attributes
属性来设置对象的默认状态
class Order extends Model { use HasStateMachine; /** * Default model's attributes. * * @var array */ protected $attributes = [ 'status' => 'pending' ]; /** * StateMachine configuration * * @return array */ protected function stateMachineConfig() : array { // This is the name of the graph in the "state-machine.php" config file return [ 'graph' => 'order', ]; } }
事件
状态机提供了两个主要钩子,用于控制状态之间的转换
- 转换中
- 已转换
指向每个状态更改之前和之后的状态。
在下面的示例中,在您的 EventServiceProvider
中,您可以在订单的 "accept" 转换之前和之后指定。
class EventServiceProvider extends ServiceProvider { /** * The event listener mappings for the application. * * @var array */ protected $listen = [ 'state_machine.transitioning.order.accept' => [ ListenBeforeOrderIsAccepted::class, ], 'state_machine.transited.order.accept' => [ ListenAfterOrderIsAccepted::class, ], ]; }
事件的名称是使用以下约定动态组成的
// Before trantion execution
state_machine.transitioning.[class_name].[transition_name]
// After trasition is executed
state_machine.transited.[model_class_name].[transition_name]
这样,您可以在发生特定转换时将监听器附加到特定对象上。
许可证
本软件包采用MIT许可证。