The thing is these those two events are never called, i mean i have an beforeSave() event that works perfectly, but for these two, it doesn’t seem to be working.
Because I’ve never had to reference the parent using a behavior, but thanks for the tip, maybe if I understood your application I would know why a behavior wouldn’t be preferred.
I just took a look and as far as i saw, the behavior needs to have methods that are called by events, therefore, for using a behavior there needs to be an event attached of the component. I might be wrong at this point, but i’ll look deeper into these.
@twisted, I’m pretty new to behaviors too so thanks for the links, I’ve seen a few of them before but maybe I should review. I thought I would share a simple example behavior with you.
This behavior send an email to an administrator when a comment is made to a blog entry.
The timestamp behavior handles timestamping the comment and my own home rolled CommentsBehavior emails the admin.
public function afterSave($event)
{
// this is the record being saved.
if ($this->getOwner()->getIsNewRecord())
{
$this->MailAdmin();
}
}
function MailAdmin ()
{
$model = $this->getOwner();
$post = Post::model()->findByPk($model->post_id);
$message = '<p><b>'.$post->title.'</b></p>';
$message .= $post->content.'<br />';
$message .= '<p><b>Comment:</b>'.$model->content;
$message .= '<br /><a href="http://www.tatacentre.ca/admin/index.php?r=post/view&id='.$post->id.'">Click here to view the blog entry</a>';
$mailer = Yii::createComponent('application.extensions.mailer.EMailer');
/* other stuff removed for clarity */
$mailer->MsgHTML($message);
$mailer->Send();
return;
}
}
Notice that email is only sent when the record is created, when the admin logs in and approves the comment no further action occurs. This is a down and dirty example of a behavior and it is quite specific to the model, ideally behaviors can be re-used on various models, like the timestamp example.
I still need to better understand events
In this case, I did not raise an event, the event was the record being saved.
It gives you an idea on how an event should be created in order to be attached .
Anyway, these two topics(event&behavior) are very little explained and i believe there needs to be clear example on how these should be used.
Searching google will return a single relevant article from the Yii wiki, but that article is not explained in detail, after reading it, you have more questions than before doing it, so it seems that for now, everyone is on his own when learning events/behaviors.