定义状态,定义转换和回调:剩下的由我们来做。 硬编码状态的时代已经结束了!
{
"require": {
"winzou/state-machine": "~0.1"
}
}
为了使用状态机,首先需要定义一个图。图是状态、转换和可选的回调的定义; 所有都连接到域的对象上。 多个图形可以附加到同一个对象。
让我们为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'), // 是否仅在转换到此状态时才调用
'do' => function() { var_dump('guarding to cancelled state'); return false; }
)
),
'before' => array(
'from-checkout' => array(
'from' => array('checkout'), // 是否只对来自此状态的转换调用
'do' => function() { var_dump('from checkout transition'); }
)
),
'after' => array(
'on-confirm' => array(
'on' => array('confirm'), // 只会在交接时被调用吗
'do' => function() { var_dump('on confirm transition'); }
),
'to-cancelled' => array(
'to' => array('cancelled'), // 是否仅在转换到此状态时才调用
'do' => function() { var_dump('to cancel transition'); }
),
'cancel-date' => array(
'to' => array('cancelled'),
'do' => array('object', 'setCancelled'),
),
)
)
);
所以,在前面的例子中,图形有6种可能的状态,这些状态可以通过对对象应用一些转换来实现。例如,当创建一个新 DomainObject
, 你可以应用 'create' 转换到对象,然后它的状态变为 pending.
状态机是实际操作对象的对象。 通过使用状态机,您可以测试是否可以应用转换,实际应用转换,检索当前状态,等等。 状态机是特定于一对 对象 + 图 这意味着如果你想操纵其它对象, 或者用这些对象的其它图, 您需要另一个状态机.
工厂帮助您获得这些对象+图的状态机。 你给它一个对象和一个图名称, 它会把这对状态机对象返回给你。如果你想在你的Symfony2应用程序中使用这个工厂服务,请看 corresponding StateMachineBundle.
请参阅examples
文件夹中的几个例子
回调用于保护转换或在应用转换之前或之后执行一些代码。
Guarding 回调必须返回 bool
. 如果守卫返回 false
, 不能执行转换。
This library has been highly inspired by https://github.com/yohang/Finite, but has taken another direction.
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。