-1

Sometimes we have Models and Controllers where the function __construct() just doesn't do anything, but is sitting on the top of all the methods in CodeIgniter's models and controllers. A lot of CodeIgniter books teach it that way. Following is the example of a __construct(), where it isn't doing anything, and if you remove it the application doesn't break.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Register_model extends CI_Model {

  public function __construct()
  {
    parent::__construct();
  }

  public function register_user($data)
  {
    return ($this->db->insert('users', $data)) ? true : false;
  }

}

/* End of file Register_model.php */
/* Location: ./application/models/Register_model.php */

If we instead use it like as follow (without __construct()), the application won't break.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Register_model extends CI_Model {

  public function register_user($data)
  {
    return ($this->db->insert('users', $data)) ? true : false;
  }

}

/* End of file Register_model.php */
/* Location: ./application/models/Register_model.php */

So what is better (or good practice) in this case, to use a __construct(), or not to use it?

2

In your example, the constructor is just calling parent constructor and isn't adding anything to it. e.g.,

  1. It isn't initializing any helpers or libraries which you need in other methods of the class.
  2. You aren't adding any code which you need to be executed during the time this class loads (or the class adds to the super object in case of codeigniter).

So in this case you don't need to add a __constructor inside the model or controller unless one of the above two conditions meet.

Not the answer you're looking for? Browse other questions tagged or ask your own question.