Jump to content
Larry Ullman's Book Forums

Preference


Edward
 Share

Recommended Posts

"Which approach you take–validation scenarios or events–is largely a matter of

preference, as both will do the trick. With event handling, you are moving more of

the logic out of the rules and into new methods, which can make for cleaner code."

 

Method1:

# protected/models/AnyModel.php::rules()

array('date_entered', 'default', 'value'=>new CDbExpression('NOW()'), 'on'=>'insert'),

array('date_updated', 'default', 'value'=>new CDbExpression('NOW()'), 'on'=>'update'),

 

Method2:

# protected/models/AnyModel.php

public function beforeSave() {

if ($this->isNewRecord) {

$this->created = new CDbExpression('NOW()');

} else {

$this->modified = new CDbExpression('NOW()');

}

return parent::beforeSave();

}

 

Edward: I started out i using Method2 to do this, but i thought method1 that you suggested using the default was much better. As in my User model i have loads of methods already and therefore trying to reduce them is a good. I also found in beforeSave and other event handling methods like this that i had to test on other scenario's rather than the predefined 'insert' and 'update'. So it just seems tidier to keep defaults like these using rules() in Method1. Just my thoughts.

 

To Larry: I was very impressed with "Working with Models" i have learned quite a lot of extra simplifying coding tips just reading through that. Yii should of had something like this a long time ago. I don't think it would be a bad idea for you to write a eBook on how to use ZendFramework 2 because they have nothing useful like this either.

  • Upvote 1
Link to comment
Share on other sites

Hello Edward. On a simple matter, such as using NOW() for dates, I would use the default value rule myself. I prefer to use the separate method when more logic is required.

 

Thanks for the nice words on the chapter. I'm glad you liked it. I also appreciate the suggestion of writing one on Zend Framework, but I don't use ZF as the basis of a site, I don't really care for it all that much, and so I wouldn't do that. But thanks.

  • Upvote 1
Link to comment
Share on other sites

 Share

×
×
  • Create New...