Blog Tutorial -- Comment Model Questions

In the tutorial, specifically this page

The author writes

Why put the comment code in the post section? I understand the reasoning, but couldn’t one put the actual comment functions addComment() and newComment() in the Comment model/controller and then just reference them accordingly in the Post model/controller classes?

I suppose you’d need to create references to the comment instance properly and it could be a little cumbersome, but at least you’d separate your Post code from your Comment code?

Or, is it common practice to have a mother class handle issues with the child functionality. I.e., mother being "post" and child being "comments"

For reference:


	protected function newComment($post) { //  controllers\PostController.php

		$comment = new Comment();


		if (isset($_POST['ajax']) && $_POST['ajax'] === 'comment-form') {

			echo CActiveForm::validate($comment);




		if (isset($_POST['Comment'])) {

			$comment->attributes = $_POST['Comment'];

			if ($post->addComment($comment)) {

				if ($comment->status == Comment::STATUS_PENDING)

					Yii::app()->user->setFlash('commentSubmitted', 'Thank you for your comment. Your comment will be posted once it is approved.');






		return $comment;


	public function addComment($comment) { // models\Post.php

		if (Yii::app()->params['commentNeedApproval'])







		return $comment->save();



Hi Peak Reacher,

You should not assume a strong relation between a model and a controller.

A single controller using multiple models is a common practice.

Usually we create both the model and the controller for some entity, Post model and PostController for example, but they are not to be considered as an unbreakable pair.

Or, it’s recommended to code your Post model without any dependence to the PostController.

All other controllers than PostController should be free to use the Post model, without any help from the PostController.

This section of the guide will be helpful.

Yes it is.