Class yii\behaviors\OptimisticLockBehavior

Inheritanceyii\behaviors\OptimisticLockBehavior » yii\behaviors\AttributeBehavior » yii\base\Behavior » yii\base\BaseObject
Implementsyii\base\Configurable
Available since version2.0.16
Source Code https://github.com/yiisoft/yii2/blob/master/framework/behaviors/OptimisticLockBehavior.php

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 \yii\behaviors\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::className(),
    ];
}

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 yii\db\BaseActiveRecord::optimisticLock() for details on how to enable optimistic lock.

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
$attributes array List of attributes that are to be automatically filled with the value specified via $value. yii\behaviors\AttributeBehavior
$owner yii\base\Component|null The owner of this behavior yii\base\Behavior
$preserveNonEmptyValues boolean Whether to preserve non-empty attribute values. yii\behaviors\AttributeBehavior
$skipUpdateOnClean boolean Whether to skip this behavior when the $owner has not been modified yii\behaviors\OptimisticLockBehavior
$value mixed The value that will be assigned to the current attributes. yii\behaviors\OptimisticLockBehavior

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. yii\base\BaseObject
__construct() Constructor. yii\base\BaseObject
__get() Returns the value of an object property. yii\base\BaseObject
__isset() Checks if a property is set, i.e. defined and not null. yii\base\BaseObject
__set() Sets value of an object property. yii\base\BaseObject
__unset() Sets an object property to null. yii\base\BaseObject
attach() Attaches the behavior object to the component. yii\behaviors\OptimisticLockBehavior
canGetProperty() Returns a value indicating whether a property can be read. yii\base\BaseObject
canSetProperty() Returns a value indicating whether a property can be set. yii\base\BaseObject
className() Returns the fully qualified name of this class. yii\base\BaseObject
detach() Detaches the behavior object from the component. yii\base\Behavior
evaluateAttributes() Evaluates the attribute value and assigns it to the current attributes. yii\behaviors\AttributeBehavior
events() Declares event handlers for the $owner's events. yii\behaviors\OptimisticLockBehavior
hasMethod() Returns a value indicating whether a method is defined. yii\base\BaseObject
hasProperty() Returns a value indicating whether a property is defined. yii\base\BaseObject
init() Initializes the object. yii\base\BaseObject
upgrade() Upgrades the version value by one and stores it to database. yii\behaviors\OptimisticLockBehavior

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
getLockAttribute() Returns the column name to hold the version value as defined in optimisticLock(). yii\behaviors\OptimisticLockBehavior
getValue() Returns the value for the current attributes. yii\behaviors\OptimisticLockBehavior

Property Details

$skipUpdateOnClean public property

Whether to skip this behavior when the $owner has not been modified

public boolean $skipUpdateOnClean false
$value public property

In case of null value it will be directly parsed from getBodyParam() or set to 0.

The value that will be assigned to the current attributes. 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
}
public mixed $value null

Method Details

attach() public method

Attaches 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.

public void attach ( $owner )
$owner yii\base\Component

The component that this behavior is to be attached to.

events() public method

Declares 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',
]
public array events ( )
return array

Events (array keys) and the corresponding event handler methods (array values).

getLockAttribute() protected method (available since version 2.0.16)

Returns the column name to hold the version value as defined in optimisticLock().

protected string getLockAttribute ( )
return string

The property name.

throws yii\base\InvalidCallException

if optimisticLock() is not properly configured.

getValue() protected method

Returns 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.

protected mixed getValue ( $event )
$event yii\base\Event

The event that triggers the current attribute updating.

return mixed

The attribute value

upgrade() public method (available since version 2.0.16)

Upgrades the version value by one and stores it to database.

$model->upgrade();
public void upgrade ( )
throws yii\base\InvalidCallException

if owner is a new record.