I’m reading Yii Cookbook 1.1 and one of the first things discussed are events. The example code shows how to trigger an event every time a comment is added to a post. Here’s how it’s implemented:
protected/components/NewCommentEvent.php
class NewCommentEvent extends CModelEvent
{
public $post;
public $comment;
}
protected/models/post.php
class Post extends CActiveRecord
{
public function addComment(Comment $comment)
{
$comment->post_id = $this->id;
$event = new NewCommentEvent($this);
$event->post = $this;
$event->comment = $comment;
//trigger event
$this->onNewComment($event);
return $event->isValid;
}
public function onNewComment($event)
{
$this->raiseEvent('onNewComment', $event);
}
}
protected/components/Notifier.php
class Notifier
{
public function comment($event)
{
$text = 'there was a new comment from '.$event->comment->author.' on post '.$event->post->title;
mail('mail@mail.com', 'New Comment', $text);
}
}
protected/controllers/PostController.php
class PostController extends CController
{
public function actionAddComment()
{
$post = Post::model()->findByPk(10);
$notifier = new Notifier();
//attach event handler
$post->onNewComment = array($notifier, 'comment');
$comment = new Comment();
$comment->author = 'Sam Dark';
$comment->text = 'Yii events';
//adding component
$post->addComment($comment);
}
}
That’s a lot of code. How is it different from having CommentController request Comment model to add a comment to a post and send an email without using events?
I mean if there’s a method actionAddComment, you can just slap “mail(‘mail@mail.com’, ‘New Comment’, $text);” in that method and every time a comment is added, email will be sent, and the code is significantly shorter.
I understand use of events in JS and it makes sense to me, but in PHP it seems so unnecessary. What am I missing here?