PHP code example of tsmsogn / cakephp-state-machine
1. Go to this page and download the library: Download tsmsogn/cakephp-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/ */
tsmsogn / cakephp-state-machine example snippets
public function onBeforeTransition($currentState, $previousState, $transition) {
// will fire on all transitions
}
public function onAfterIgnite($currentState, $previousState, $transition) {
// will fire after the ignite transition
}
public function onStateChange($newState) {
// will fire on all state changes
}
public function onStateIdling($newState) {
// will fire on the idling state
}
App::uses('StateMachineBehavior', 'StateMachine.Model/Behavior');
class VehicleModel extends AppModel {
public $useTable = 'Vehicle';
public $actsAs = array('StateMachine.StateMachine');
public $initialState = 'parked';
public $transitionRules = array(
'ignite' => array(
'role' => array('driver'),
'depends' => 'has_key'
)
);
public $transitions = array(
'ignite' => array(
'parked' => 'idling',
'stalled' => 'stalled'
),
'park' => array(
'idling' => 'parked',
'first_gear' => 'parked'
),
'shift_up' => array(
'idling' => 'first_gear',
'first_gear' => 'second_gear',
'second_gear' => 'third_gear'
),
'shift_down' => array(
'first_gear' => 'idling',
'second_gear' => 'first_gear',
'third_gear' => 'second_gear'
),
'crash' => array(
'first_gear' => 'stalled',
'second_gear' => 'stalled',
'third_gear' => 'stalled'
),
'repair' => array(
'stalled' => 'parked'
),
'idle' => array(
'first_gear' => 'idling'
),
'turn_off' => array(
'all' => 'parked'
)
);
public function __construct($id = false, $ds = false, $table = false) {
parent::__construct($id, $ds, $table);
$this->on('ignite', 'after', function($prevState, $nextState, $transition) {
// the car just ignited!
});
}
// a shortcut method for checking if the vehicle is moving
public function isMoving() {
return in_array($this->getCurrentState(), array('first_gear', 'second_gear', 'third_gear'));
}
// the dependant function for "ignite"
public function hasKey($role) {
return $role == 'driver';
}
}
class Controller .... {
public function method() {
$this->Vehicle->create();
$this->Vehicle->save(array(
'Vehicle' => array(
'title' => 'Toybota'
)
));
// $this->Vehicle->getCurrentState() == 'parked'
if ($this->Vehicle->canIgnite(null, 'driver')) {
$this->Vehicle->ignite(null, 'driver');
$this->Vehicle->shiftUp();
// $this->Vehicle->getCurrentState() == 'first_gear'
}
}
}
$model->toDot()
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.