Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter 2 difference between index and __construct and what to put in __construct

When is __construct called and when is index called? And are there any other differences?

And what to put in __construct? Whats the best practice, should I put $this->load calls... ? what else?

class Site extends CI_Controller {

      public function __construct() {

          parent::__construct();
          echo 'Hello World2';

     }

     public function index() {

          echo 'Hello World1';

     }
}
like image 254
VoX Avatar asked Aug 26 '26 14:08

VoX


1 Answers

__construct() is called first, then according to URL is called index() or other functions.

public function __construct() should contain:

  1. allocating resources used in entire class ex. $this->load
  2. check user authentication (if entire class requires it)

public function index() should contain:

  1. allocating resources used only in this function
  2. calling views or displaying anything

it is bad design if public function __construct() contain:

  1. Displaying anything
  2. Any code required only for one function.
like image 92
Igor S. Avatar answered Aug 28 '26 04:08

Igor S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!