Suppose you need to call a function called get_user_info that retrieves user information from a database. You may have a function like this:
class Home extends Controller { function __construct() { parent::__construct(); } function index() { $user = $this->get_user_info($_SESSION['user_id']); echo "Hello " . $user['first_name']; } function get_user_info($user_id) { $query = $this->db->query("SELECT * FROM users WHERE user_id = ?", array($user_id)); return $query->row_array(); } }
However, what if you needed to call get_user_info on another page?
In this case, you have to copy and paste the function on each page, which makes it difficult to support if you have many pages (what if you need to change the JOIN request to another table?)
It is also contrary to do not repeat the principle .
Models are designed to handle all the logic and presentation of data, returning data that is already loaded into the view. Most often they are used as a way of grouping database functions, which makes it easy to change them without changing all your controllers.
class User extends Model { function __construct() { parent::Model(); } function get_user_info($user_id) { $query = $this->db->query("SELECT * FROM users WHERE user_id = ?", array($user_id)); return $query->row_array(); } }
In the above example, we created a model called user . In our home controller, we can now change the code as follows:
class Home extends Controller { function __construct() { parent::__construct(); } function index() { $this->load->model('user'); $user = $this->user->get_user_info($_SESSION['user_id']); echo "Hello " . $user['first_name']; } }
And now you can change your get_user_info function without changing the number of X controllers that rely on the same function.
source share