-
Hi, First of all thanks a lot for the wonderful package! I would like to define the states and the transitions outside of the model, in a configuration file. This is because, in my application, states are different by customer and should be configurable. The idea is to have all the states and transition classes developed and by configuration define the valid states workflow. Any easy way of achieving this? Thanks a lot! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hi, If anyone needs to provide this same functionality, this is the approach that we have followed: config/statemachine.php <?php
return [
'application' => [
'events_class' => 'App\State\ApplicationState\Events\ApplicationStateChanged',
'places' => [
'App\State\ApplicationState\Places\PendingState',
'App\State\ApplicationState\Places\SearchingState',
'App\State\ApplicationState\Places\SearchFailedState'
],
'initial_place' => 'App\State\ApplicationState\Places\PendingState', // defaults to the first place if omitted
'transitions' => [
'App\State\ApplicationState\Transitions\PendingToSearching' => [
'from' => 'App\State\ApplicationState\Places\PendingState',
'to' => 'App\State\ApplicationState\Places\SearchingState',
// optional transition-level metadata
'metadata' => [
// any data
]
],
'App\State\ApplicationState\Transitions\SearchingToSearchFailed' => [
'from' => 'App\State\ApplicationState\Places\SearchingState',
'to' => 'App\State\ApplicationState\Places\SearchFailedState'
]
],
]
]; Usage in Model <?php
namespace App\State\ApplicationState;
use Spatie\ModelStates\State;
use App\Models\NewApplications;
use Spatie\ModelStates\StateConfig;
abstract class ApplicationState extends State
{
public static function config(): StateConfig
{
$statesConfig = config("statemachine.application");
$o = parent::config();
// Call the `default()` method taking the value from the workflow object initial_place attribute
$initialPlace = $statesConfig['initial_place'];
$o->default($initialPlace);
if (isset($statesConfig['events_class'])) {
$o->stateChangedEvent($statesConfig['events_class']);
}
// Call `registerState()` for each item in places
foreach ($statesConfig['places'] as $place) {
$o->registerState($place);
}
// Call `allowTransition` for each transition in the transition array
foreach ($statesConfig['transitions'] as $transitionName => $transitionData) {
$fromState = $transitionData['from'];
$toState = $transitionData['to'];
$transitionClass = $transitionName;
$o->allowTransition($fromState, $toState, $transitionClass);
}
return $o;
}
} |
Beta Was this translation helpful? Give feedback.
Hi,
If anyone needs to provide this same functionality, this is the approach that we have followed:
config/statemachine.php