composerdelivery / state-machine
一个非常轻量级但功能强大的PHP状态机
0.4.2
2020-04-02 06:54 UTC
Requires
- php: ^7.1.3
- symfony/event-dispatcher: ^4.3|^5.0
- symfony/expression-language: ^4.3|^5.0
- symfony/property-access: ^4.3|^5.0
Requires (Dev)
- phpunit/phpunit: ^8.5|^9.0
- twig/twig: ^3.0
Suggests
- twig/twig: Access the state machine in your twig templates (^3.0)
README
定义您的状态,定义您的转换和回调:我们来做其余的事情。硬编码状态的年代已经过去了!
安装(通过composer)
{ "require": { "winzou/state-machine": "~0.4" } }
用法
配置状态机图
为了使用状态机,您首先需要定义一个图。图是状态、转换以及可选的回调的定义;所有这些都附加在您的领域对象上。可以将多个图附加到同一对象上。
让我们为我们的 DomainObject
对象定义一个名为 myGraphA 的图
$config = array( 'graph' => 'myGraphA', // Name of the current graph - there can be many of them attached to the same object 'property_path' => 'stateA', // Property path of the object actually holding the state 'states' => array( 'checkout', 'pending', 'confirmed', 'cancelled' ), 'transitions' => array( 'create' => array( 'from' => array('checkout'), 'to' => 'pending' ), 'confirm' => array( 'from' => array('checkout', 'pending'), 'to' => 'confirmed' ), 'cancel' => array( 'from' => array('confirmed'), 'to' => 'cancelled' ) ), 'callbacks' => array( 'guard' => array( 'guard-cancel' => array( 'to' => array('cancelled'), // Will be called only for transitions going to this state 'do' => function() { var_dump('guarding to cancelled state'); return false; } ) ), 'before' => array( 'from-checkout' => array( 'from' => array('checkout'), // Will be called only for transitions coming from this state 'do' => function() { var_dump('from checkout transition'); } ) ), 'after' => array( 'on-confirm' => array( 'on' => array('confirm'), // Will be called only on this transition 'do' => function() { var_dump('on confirm transition'); } ), 'to-cancelled' => array( 'to' => array('cancelled'), // Will be called only for transitions going to this state 'do' => function() { var_dump('to cancel transition'); } ), 'cancel-date' => array( 'to' => array('cancelled'), 'do' => array('object', 'setCancelled'), ), ) ) );
因此,在先前的例子中,图有6个可能的状态,可以通过对对象应用一些转换来实现这些状态。例如,当创建一个新的 DomainObject
时,您会对对象应用 'create' 转换,之后它的状态将变为 pending。
使用状态机
定义
状态机是实际操作您的对象的那个对象。通过使用状态机,您可以测试是否可以应用转换,实际应用转换,检索当前状态等。 一个状态机针对一对对象 + 图。 这意味着如果您想操作另一个对象,或者使用另一个图操作同一对象,您需要另一个状态机。
工厂可以帮助您获取这些对象 + 图的状态机。您向它提供一个对象和一个图名,它将返回这对的状态机。如果您想在您的Symfony2应用程序中将其作为服务使用,请参阅 相应的StateMachineBundle。
用法
请参考 examples
文件夹中的多个示例。
回调
回调用于保护转换或执行应用转换之前或之后的某些代码。
保护回调必须返回一个 bool
。如果保护返回 false
,则不能执行转换。
致谢
这个库高度受到了 https://github.com/yohang/Finite 的启发,但采取了不同的方向。