PHP code example of weiwenhao / state-machine

1. Go to this page and download the library: Download weiwenhao/state-machine library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

weiwenhao / state-machine example snippets




namespace App\Graphs;

use Illuminate\Database\Eloquent\Model;
use Weiwenhao\StateMachine\Graph;

class TestGraph extends Graph
{
    /**
     * 所有可选的状态
     * @var array
     */
    protected $states = [
        'cart',
        'new',
        'cancelled',
        'fulfilled'
    ];

    /**
     * 初始状态
     * @var string
     */
    protected $initState = 'cart';

    /**
     * 定义状态之间的转换
     * @var array
     */
    protected $graph= [
        'create' => [
            'from' => ['cart'],
            'to' => 'new',
        ],
        'cancel' => [
            'from' => ['new'],
            'to' => 'cancel',
        ],
        'fulfilled' => [
            'from' => ['new'],
            'to' => 'fulfilled'
        ]
    ];

    /**
     * Model中用于进行状态转换的key 默认使用state字段
     * @var string
     */
    protected $key = 'state';

    /**
     * 转换发生时调用的回调(后置回调)
     * @param $object
     * @return string
     */
    public function onCreate(Model $object)
    {
        return 'created';
    }
}




namespace App\Enums;

interface OrderState
{
    const NEW = 0;
    const CANCELLED = 1;
    const FULFILLED = 2;
}




# TestGraph.php

public function onCancel($order)
{
    // cancel..
}