wppd/state-machine

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

该软件包的规范存储库似乎已丢失,因此该软件包已被冻结。

0.4.1 2020-03-05 22:36 UTC

This package is auto-updated.

Last update: 2021-02-20 11:28:21 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 的极大启发,但已经走向了另一个方向。