Confused With Events

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?

I’ld say this code in the cookbook is an example of how an event can be used.

The main advantage is loose coupling which leaves the possibility to add/remove action in case the event occurs.

Also, in this case, the controller action does not need to know about the Event parameters themselves and the Notifier code can be reused accross Controller actions for instance.

Have a look at a yii wiki page on behaviors and events to get a glimpse of how behaviors leverage on events.

Thanks, makes a little more sense now :)