Define the lifecycle of a model by defining allowed status changes in terms of a state machine.
This is an extension for the Yii 2 PHP framework.
Installation is recommended to be done via composer by running:
composer require cebe/yii2-lifecycle-behavior
Alternatively you can add the following to the require
section in your composer.json
manually
and run composer update
afterwards:
"cebe/yii2-lifecycle-behavior": "~2.0.0"
You can add the behavior to an ActiveRecord class. It does not work with yii\base\Model
because it relies on the old-attribute feature which is only available in active record.
You can add the behavior to the model by creating a behaviors()
method if there is none yet, or
add it to the list of exising behaviors.
The following example shows how to define the allowed status changes:
public function behaviors()
{
return [
'lifecycle' => [
'class' => cebe\lifecycle\LifecycleBehavior::class,
'validStatusChanges' => [
'draft' => ['ready', 'delivered'],
'ready' => ['draft', 'delivered'],
'delivered' => ['payed', 'archived'],
'payed' => ['archived'],
'archived' => [],
],
],
];
}
The above state transitions can be visualized as the following state machine:
By default, the behavior will validate the status
attribute of the record, when validate()
or save()
is called
and add a validation error in case state has changed in a way that is not allowed.
statusAttribute
property of the behavior.validationErrorMessage
property of the behavior.
The place holders {old}
and {new}
are being replaced with the corresponding status values.The behavior may also be used to validate status changes in program flow. This is different to user input validation as described above, because program flow will be aborted by an exception in this case. For user input, the recipient of the error message is the user, when status is not changed by the user, the recipient of the error is the developer.
By default status field is validated both, on validation and on update. To disable one of the methods, you may configure
the $events
propery, which is by default:
'events' => [
BaseActiveRecord::EVENT_BEFORE_VALIDATE => 'handleBeforeValidate',
BaseActiveRecord::EVENT_BEFORE_UPDATE => 'handleBeforeSave',
]
Comments