PHP code example of sokil / php-state

1. Go to this page and download the library: Download sokil/php-state 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/ */

    

sokil / php-state example snippets




// create state machine builder
$machineBuilder = new MachineBuilder();

// configure states
$machineBuilder
    ->addState(function(StateBuilder $builder) {
        $builder->setName('new');
    })
    ->addState(function(StateBuilder $builder) {
        $builder
            ->setName('in_progress')
            ->setMetadata([
                'label' => 'In progress'
            ]);
    })
    ->addState(function(StateBuilder $builder) {
        $builder->setName('done');
    });
    
// set initial state
$machineBuilder->setInitialState('new');

// configure transitions between states
$machineBuilder
    ->addTransition(function(TransitionBuilder $builder) {
        $builder
            ->setName('set_in_progress')
            ->setInitialStateName('new')
            ->setResultingStateName('in_progress')
            ->setAcceptCondition(function() {
                // conditions when accepted to transit from "new" state to "in_progress"
                return true;
            });
    })
    ->addTransition(function(TransitionBuilder $builder) {
        $builder
            ->setName('set_done')
            ->setInitialStateName('in_progress')
            ->setResultingStateName('done');
    });
    
// create machine
$machine = $machineBuilder->getMachine();

// process transition
$state = $machine->process('set_in_progress')->getCurrentState();



// YAML
$configuration = new YamlConfiguration('config.yaml');

// PHP Array
$configuration = new ArrayConfiguration('config.php');
// or
$configuration = new ArrayConfiguration([...state configuration...]);

// JSON
$configuration = new JsonConfiguration('config.json');

// Configure
$machineBuilder = new MachineBuilder();
$machine = $machineBuilder->configure($configuration)->getMachine();


$configuration = new YamlConfiguration('config.yaml', ['pecl' => false]);