Sunday, April 15, 2012

Optimistic Concurrency Control with Yii's Activerecord

Here's how to do Optimistic Concurrency Control with Yii's ActiveRecord:
class OCCActiveRecord extends CActiveRecord{

  public $checksum = null;

  public function afterFind(){

    /* get a checksum of all the attribute values after reading a record from db */

    $this->checksum = md5(implode('', $this->getAttributes(false)));


    public function rules(){

/* use an exist validator to make sure that a record with the same checksum is still in db. if it's been modified, then checksums will be different */

 return array(
     array('id', 'exist', 'message'=>'This record was modified after you read it', 'on'=>'update', 'criteria'=>array('condition'=>'md5(concat('.implode(',',$this->attributeNames()).'))=:checksum', 'params'=>array('checksum'=>$this->checksum)))

Just a rough sketch, but you get the idea.

You could also modify this to be a behavior. Works only with MySQL AFAIK.


  1. I was seeking for hire yii developers and set down up on your mail and i should state thanks for distributing such helpful information.

  2. You can also have a look at an extension I've written: Its a base class for my model classes and has optimistic locking implementation within. In its turn, its based on code shared on the Yii forums (links are within that extension's page, IIRC).

  3. hi,
    this is not working.. can you please have a look..

  4. It is useful code for us.. thanks for sharing. If you like to learn about Yii 2.0 beta version, please visit this video: