Using Models in CodeIgniter

Can someone explain to me when it is good practice to use models in CI? The Wikipedia article referred to CI models as โ€œcompletely optional and rarely needed,โ€ is that true?

+4
source share
7 answers

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.

+14
source

Not!! It is not true. Models are used as a layer between your controller and the database. Best practice MVC is subjective at best. People use it in different ways. A frame like CodeIgniter is great because it provides this level of flexibility. Other frameworks are much stricter. I am a general, I try to make my controllers very small and specific, and add a lot of code to the model (interaction with db and analysis results, etc.).

+2
source

Well, the "model" data about the reviewers is most likely from the database (which means that your rows are returned from the database, and the model contains the sending data, it just says). There is no need to use the database level specified by CI - it is true - you can replace it with another if you want, but that they are "rarely used" just do not correspond to reality.

+1
source

You should use models to avoid code duplication (do not repeat yourself). I think that most (almost all) applications built with codeigniter will use some models.

Perhaps the article belongs to the class of active recording, which is optional for use in models. An active record, which I find useful for creating, updating, and deleting, but you will most likely need sql for any slightly complex reads. It is worth noting that these are not just databases that you can use in models. The model can use web services or flat files or any other data source.

I thought of models only as a database layer. They should not be, this creates a bloat in your controllers. Using fat controllers will ultimately slow you down. Put the whole model model in the model if you can and just use the controller for logic.

+1
source

There is a principle called the "fat model / skinny controller" that you might like to look at, suggests that the weight of your processing should be done in model files, as against controllers. This is confirmed by the fact that you do not repeat the principle described above, as well as promote reuse.

I found, using this principle, that I have a set of common, reusable controllers, each of which uses a set of reusable models, and also, sometimes, project-specific controllers that are used only once per site. In addition, I have a cross-relationship between models. I would not be able to reuse as often as I do, without following the above principle and encapsulating as much processing as possible in the models.

This issue is discussed a lot on the net, so there is a lot of information that you can look at, but it seems that more experienced users are recommended on Code Igniter boards.

I should add that โ€œcompletely optional and rarely neededโ€ is usually not so, I would say that this is simply wrong in all but the simplest cases - the simplest cases are static pages that do not integrate with the database and itโ€™s easy to consist of several loaded views, but even then using a model with a function to retrieve a common set of views for each page would be worthwhile.

+1
source

Models are intended for business logic (in ideal cases .. maybe for discussion, some people put logic in the controller) and database communications within the framework of MVC.

Read the codeigniter user guide for more information on models.

http://codeigniter.com/user_guide/general/models.html

0
source

My big model has a lot of methods.

  class Shortcode_model extends CI_Model { public function __construct() { parent::__construct(); $this -> load -> library('session'); } /** * Misc functions */ /** * read keyword . * * @return void * @author Chinthaka **/ public function read($id) { $this -> db -> select(); $this -> db -> from('short_code'); $this -> db -> where('id', $id); $query = $this -> db -> get(); $result = $query -> row(); $shortcode = new stdClass(); $shortcode->id = $result->id; $shortcode->code = $result->code; $shortcode->aggregator = $result->aggregator; $shortcode->mo_pp_id = $result->mo_pp_id; $shortcode->mt_free_pp_id = $result->mt_free_pp_id; $shortcode->mt_bill_pp_id = $result->mt_bill_pp_id; $shortcode->partner_role_id = $result->partner_role_id; $shortcode->partner_role_pass = $result->partner_role_pass; $shortcode->product_id = $result->product_id; $shortcode->billable = $result->billable; // $shortcode->created = $result->created; // $shortcode->changed = $result->changed; $shortcode->status = $result->status; //print_r($shortcode); return $shortcode; } public function read_operator($telco_id){ $this -> db -> select(); $this -> db -> from('operator'); $this -> db -> where('telco_id', $telco_id); $query = $this -> db -> get(); $result = $query -> row(); $operator = new stdClass(); $operator->id = $result->id; $operator->code = $result->telco_id; $operator->name = $result->telco_name; return $operator; } /** * create keyword . * * @return void * @author Chinthaka **/ public function create($arr_data) { $this -> db -> insert('short_code', $arr_data); //$stock['stock_id'] = $this->db->insert_id(); //return $query->result(); //return $keywords; } /** * update keyword . * * @return void * @author Chinthaka **/ public function update($arr_data) { $this -> db -> where('id', $arr_data['id']); $this -> db -> update('short_code', $arr_data); } /** * delete keyword . * * @return void * @author Chinthaka **/ public function delete($id) { $this -> db -> where('id', $id); $this -> db -> delete('short_code'); } /** * get all enabled shortcodes stored in the database. * * @return $shortcodess * @author Chinthaka **/ public function all_enable_shortcodes() { $this -> db -> select(); $this -> db -> from('short_code'); $this -> db -> where('status', 'enable'); $this -> db -> order_by("code"); $query = $this -> db -> get(); $result = $query -> result_array(); //echo mysql_num_rows($result); $shortcodes = array(); foreach ($result as $row) { $shortcode = $this -> read($row['id']); array_push($shortcodes, $shortcode); } /*while($data = $this->db->call_function('fetch_row', $result )) { $shortcode = $this->read($data['id']); array_push($shortcodes,$shortcode); }*/ return $shortcodes; } /** * check shortcode is exist. * * @return boolean * @author Chinthaka **/ function is_exists($shortcode, $id = 0) { $this -> db -> where('code', $shortcode); if ($id > 0) { $this -> db -> where('id <>', $id); } $query = $this -> db -> get('short_code'); if ($query -> num_rows() > 0) { return true; } else { return false; } } public function get($short_code_id) { $query = $this->db->query('select * from short_code where id=?', array($short_code_id)); log_message('debug', $this->db->last_query()); return $query->row(); } } 
0
source

Source: https://habr.com/ru/post/1315396/


All Articles