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)));

    parent::afterFind();
  }

    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.

3 comments:

  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.

    ReplyDelete
  2. You can also have a look at an extension I've written: http://www.yiiframework.com/extension/pcbasearmodel/. 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).

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

    ReplyDelete