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.

class Timestampbehavior extends CActiveRecordBehavior 
    public function beforeSave($event){
        $currenttime=new CDbExpression('NOW()');
        return true; 

Add Timestamp To Model

I added the behavior to model

class Mymodel extends CActiveRecord
    public function behaviors(){
        return array(
    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.