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.

1 comment:

  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