Jump to content
Larry Ullman's Book Forums

Preference


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 post
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 post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...