OptimisticLockBehavior
API reference › yii › behaviors › OptimisticLockBehavior
OptimisticLockBehavior automatically upgrades a model’s lock version using the column name returned by optimisticLock().
Optimistic locking allows multiple users to access the same record for edits and avoids
potential conflicts. In case when a user attempts to save the record upon some staled data
(because another user has modified the data), a StaleObjectException exception will be thrown,
and the update or deletion is skipped.
To use this behavior, first enable optimistic lock by following the steps listed in optimisticLock(), remove the column name holding the lock version from the rules() method of your ActiveRecord class, then add the following code to it:
use yii\behaviors\OptimisticLockBehavior;
public function behaviors(){ return [ OptimisticLockBehavior::class, ];}By default, OptimisticLockBehavior will use getBodyParam() to parse the submitted value or set it to 0 on any fail. That means a request not holding the version attribute may achieve a first successful update to entity, but starting from there any further try should fail unless the request is holding the expected version number.
Once attached, internal use of the model class should also fail to save the record if the version number
isn’t held by getBodyParam(). It may be useful to extend your model class,
enable optimistic lock in parent class by overriding optimisticLock(),
then attach the behavior to the child class so you can tie the parent model to internal use while linking the child model
holding this behavior to the controllers responsible of receiving end user inputs.
Alternatively, you can also configure the $value property with a PHP callable to implement a different logic.
OptimisticLockBehavior also provides a method named upgrade() that increases a model’s
version by one, that may be useful when you need to mark an entity as stale among connected clients
and avoid any change to it until they load it again:
$model->upgrade();See also: BaseActiveRecord::optimisticLock() (for details on how to enable optimistic lock.).
Properties
Section titled “Properties”| Property | Type | Description | Defined by |
|---|---|---|---|
$attributes | array | List of attributes that are to be automatically filled with the value specified via $value. Default: []. | AttributeBehavior |
$owner | yii\ | The owner of this behavior Default: null. | yii\ |
$preserveNonEmptyValues | bool | Whether to preserve non-empty attribute values. Default: false. Available since 2.0.13. | AttributeBehavior |
$skipUpdateOnClean | bool | Default: false. Available since 2.0.8. | OptimisticLockBehavior |
$value | mixed | Default: null. | OptimisticLockBehavior |
Methods
Section titled “Methods”| Method | Description | Defined by |
|---|---|---|
__construct() | Constructor. | yii\ |
__call() | Calls the named method which is not a class method. | yii\ |
__get() | Returns the value of an object property. | yii\ |
__isset() | Checks if a property is set, i.e. defined and not null. | yii\ |
__set() | Sets value of an object property. | yii\ |
__unset() | Sets an object property to null. | yii\ |
attach() | Attaches the behavior object to the component. | OptimisticLockBehavior |
canGetProperty() | Returns a value indicating whether a property can be read. | yii\ |
canSetProperty() | Returns a value indicating whether a property can be set. | yii\ |
className() static | Returns the fully qualified name of this class. | yii\ |
detach() | Detaches the behavior object from the component. | yii\ |
evaluateAttributes() | Evaluates the attribute value and assigns it to the current attributes. | AttributeBehavior |
events() | Declares event handlers for the $owner’s events. | OptimisticLockBehavior |
hasMethod() | Returns a value indicating whether a method is defined. | yii\ |
hasProperty() | Returns a value indicating whether a property is defined. | yii\ |
init() | Initializes the object. | yii\ |
upgrade() | Upgrades the version value by one and stores it to database. | OptimisticLockBehavior |
getLockAttribute() protected | Returns the column name to hold the version value as defined in optimisticLock(). | OptimisticLockBehavior |
getValue() protected | Returns the value for the current attributes. | OptimisticLockBehavior |
Property details
Section titled “Property details”$value
Section titled “$value ”public mixed $value = nullIn case of null value it will be directly parsed from getBodyParam() or set to 0.
This can be an anonymous function,
callable in array format (e.g. [$this, 'methodName']), an Expression object representing a DB expression
(e.g. new Expression('NOW()')), scalar, string or an arbitrary value. If the former, the return value of the
function will be assigned to the attributes.
The signature of the function should be as follows,
function ($event){ // return value will be assigned to the attribute}Method details
Section titled “Method details”attach()
Section titled “attach() ”public function attach(mixed $owner): mixedAttaches the behavior object to the component.
The default implementation will set the $owner property
and attach event handlers as declared in events().
Make sure you call the parent implementation if you override this method.
Parameters
| Parameter | Type | Description |
|---|---|---|
$owner | mixed | The component that this behavior is to be attached to. |
Returns
mixed
events()
Section titled “events() ”public function events(): arrayDeclares event handlers for the $owner’s events.
Child classes may override this method to declare what PHP callbacks should
be attached to the events of the $owner component.
The callbacks will be attached to the $owner’s events when the behavior is
attached to the owner; and they will be detached from the events when
the behavior is detached from the component.
The callbacks can be any of the following:
- method in this behavior:
'handleClick', equivalent to[$this, 'handleClick'] - object method:
[$object, 'handleClick'] - static method:
['Page', 'handleClick'] - anonymous function:
function ($event) { ... }
The following is an example:
[ Model::EVENT_BEFORE_VALIDATE => 'myBeforeValidate', Model::EVENT_AFTER_VALIDATE => 'myAfterValidate',]Returns
array: Events (array keys) and the corresponding event handler methods (array values).
upgrade()
Section titled “upgrade() ”public function upgrade(): mixedUpgrades the version value by one and stores it to database.
$model->upgrade();getLockAttribute()
Section titled “getLockAttribute() ”protected function getLockAttribute(): stringReturns the column name to hold the version value as defined in optimisticLock().
Returns
string: The property name.
Throws
yii\base\InvalidCallException: if optimisticLock() is not properly configured.
Since
2.0.16
getValue()
Section titled “getValue() ”protected function getValue(mixed $event): mixedReturns the value for the current attributes.
In case of null, value will be parsed from getBodyParam() or set to 0.
This method is called by evaluateAttributes(). Its return value will be assigned
to the attributes corresponding to the triggering event.
Parameters
| Parameter | Type | Description |
|---|---|---|
$event | mixed | The event that triggers the current attribute updating. |
Returns
mixed: The attribute value