Timestamp Behavior In Yii


Normally we will add some fields in every table of application database. Ex createdby, createdon, modifiedby, modifiedon, lasteditedby, lasteditedon etc
So we have to configure model for this action. Normally we will add beforeSave() method in every model. Instead of beforeSave in every model, We will create one behavior class and add this beforeSave method. Now we can include this behavior to every model.

Create Timestamp Behavior

I created this “Timestampbehavior” class inside the “protechted/behavior” folder.

<?php
    class Timestampbehavior extends CActiveRecordBehavior 
    {
        public function beforeSave($event){
        $userid=Yii::app()->user->getId();
            $currenttime=new CDbExpression('NOW()');
            if($this->owner->isNewRecord){
            $this->owner->createdby=$userid;
            $this->owner->createdon=$currenttime;
            }
            $this->owner->lasteditedby=$userid;        
            $this->owner->lasteditedon=$currenttime;        
            return true; 
        }
    }
?>

Add Timestamp To Model

I added the behavior to model

<?php
    class Mymodel extends CActiveRecord
 { 
  public function behaviors(){
   return array(
                    'Timestampbehavior'=>array(
                        'class'=>'application.behaviors.Timestampbehavior',
                        ),
                );    
  }
    
  public static function model($className=__CLASS__)
  {
   return parent::model($className);
  }
  ................
?>  

Basically bahavior is reusable class. In our example We dont need to write more beforeSave class.