Bind database type (MySQL DATE) to a PHP class

Hi all,

I wrote a Date class to manage this datatype in my YII application.

In my MySQL database, I’ve got tables referencing DATE field. When I use generated model (extending CActiveRecord) DATE field are retrieved as string data (2011-11-24).

Is there a way to dynamicly convert DATE field to my Date class instead of String ?

Currently I override beforeSave, afterSave and afterFind to implement this feature for each class.

Is there a better way in Yii ?

Thanks for your help. Regards.

Sample code use :


public function beforeSave() {

  if (isset($this->start_date) && $this->start_date instanceof Date) {

     $this->start_date = $this->start_date->toMySqlDate();

  }

}

public function afterSave() {

  if (isset($this->start_date) && is_string($this->start_date)) {

     $this->start_date = Date::parseMysql($this->start_date);

  }

}

public function afterFind() {

  if (isset($this->start_date) && is_string($this->start_date)) {

     $this->start_date = Date::parseMysql($this->start_date);

  }

}

I think you can get rid of the first two functions by implementing __toString() in your Date class so that it will return a date in a mysql format.

Hi all,

Maybe I can use a CActiveRecordBehavior.

It will check in Metadata field type and convert from/to Date on the fly ?

I create my own CActiveRecord inheriting CActiveRecord class and add this behavior in constructor. All my class models will inherit from it.




class DateActiveRecordBehavior extends CActiveRecordBehavior {

  // do his work

}


class MyActiveRecord extends CActiveRecord {

  public function __construct() {

    $this->registerBehavior('date', new DateActiveRecordBehavior());

  }

}


class User extends MyActiveRecord {

  // do something

}



Is there a better way ?

Thanks for your help.

Herve

Read an example here: http://www.yiiframework.com/doc/guide/1.1/en/extension.use#behavior

Were you able to make it work? When use your code, I get a segmentation fault