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?
@model is used to "import" a model in the view page while the @Model represents the imported model and is where you retrieve its properties. Here you see that @model simply imports the Model object to the page while the @Model you get actual value from the retrieved model.
Fundamentally, the model “knows stuff”. It holds, the business logic of a piece of data. On the other hand, the controller, “does stuff”.
The three parts of the MVC software-design pattern can be described as follows: Model: Manages data and business logic. View: Handles layout and display. Controller: Routes commands to the model and view parts.
A controller is responsible for controlling the way that a user interacts with an MVC application. A controller contains the flow control logic for an ASP.NET MVC application. A controller determines what response to send back to a user when a user makes a browser request.
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
generally controllers are used to determine how to handle the http requests made..
There's nothing wrong in creating some functions which directly respond to the http requests.
but if it has anything to do with the DB, its better to place those function in the model, and call them from the controller.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With