I'm little confused about controller and model in MVC framework (codeIgniter). Its clear to me that controller methods calls the views and Model methods interact with database. However, I'm little confused about the following types of methods, which are called by methods in a controller.

hash_password              //returns hash password. 
valid_email               //validates email format and return true or false
is_logged                //check if session has a variable, returns true or false
generate_random_string  //generates and hashes a random string

Should they be placed in controller or in a model? Currently I place all of the above functions in a controller. Is it correct? Thanks.


I think how the password should be hashed should be dealt with by the model, because the model knows how the password is going to be stored. And maybe the last one should be in a helper file. Not sure about the rest.

Written by BoltClock

Arguably they could all go in the model, returning true/the data or false, and allowing your controller to redirect as necessary, on the pretence of "skinny controllers, fat models". I'd be inclined to go with model, model/helper, (base) controller, helper out of personal preference.

Written by Ross

Accepted Answer

I think the is_logged should be placed in the Model for User. Note that the User might be a customer in your case or any class that you have made to model a user of your service.

The valid_email and generate_random_string are more or less utility functions, which you can place in a Utility or Utilities model, so that these are reusable in various controllers in your application.

The hash_password, can be placed in either the User model or Utility model. I am more tempted to place it in Utility model, since its a hashing function and there is nothing the user cares about. However, I can imagine there can be argument(s) otherwise.

The following SO question (though for a different framework) can also serve as a rule of thumb:

Where to put custom functions in Zend Framework 1.10

Written by Ozair Kafray
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki