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