CodeIgniter Forums

Full Version: model and controller boundary
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

I am new to MVC so I dont know what I should do or not do in model or controller.

In my project 
1. when user wants to publish item, first I need to check if user exceeded its published_item_limit 
2. or if user want to publish its unpublished item I need to check if user published_item_limit

My quetion is where I should check if user exceeded limit or not in model or controller? 
I am asking it because I need to return different messages for each of this cases and in my model one method does both of these actions (insert or update)

For example, if user exceeded limit should I return 
array('success' => false, 'reason' =>'Couldnot publish, exceeded limit!') or 
array('success' => false, 'reason' =>'Couldnot update, exceeded limit!')
This is really a matter for you and your app design. Here is my rule of thumb:

Quote:1. If any non trivial piece of code (such as 'check publish limit' or similar) is to be used in more than one controller or called in more than one place or method, or used again on other projects, then move it to a model and formalise it. Otherwise code it in your controller.

There are other reasons you might want to keep even single use code in a model or library, for portability between apps for instance. So although my 'login_user' is only used by one page, the login page, it would still be a call to my authorisation library. But when I come to build my next site, I just copy the authorisation library and use all the functions as I want.

As for setting the error as you described above, I would do that in the controller anyway. So for instance you might have something like

PHP Code:
$allowance $this->publish_model->check_users_publish_limits();
if (
$allowance 0) {
  // publish or update because allowed
} else {
  // throw error message as appropriate to this point in the app
// Here I am assuming the model returns the number of publish events the user has left today. It could return True or False just based on if the user is allowed to publish or not, or anything you want of course. 

In this way, your model is not defining the error message, because it can not know the context of the check. Later if you want to use a language file for the error messages, or multi lingual error messages, you can easily alter them as required, without touching your model.

However, different people use models and libraries in different ways and for different reasons. But that is what I do with them.
Thanks PaulD for answers, its sufficiently descriptive for me