xiaobudongzhang/state-machine

一个非常轻量但强大的PHP状态机

v0.4.2 2020-04-14 09:08 UTC

This package is auto-updated.

Last update: 2024-09-14 19:53:25 UTC


README

定义你的状态,定义你的转换和回调:我们来做其余的事情。硬编码状态的年代已经过去了!

Build Status

安装(通过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的极大启发,但采取了不同的方向。