Constructor-structor, what's your function?
Filed in: ExpressionEngine, CodeIgniter
March 10, 2011
I'd like to set the record straight on the usage of class constructors in CodeIgniter and ExpressionEngine apps/addons. I have seen EE-addons and CI code examples using them where they are not necessary. To illustrate this point and make things a bit more clear, I removed the class constructor from the CodeIgniter 'welcome' controller last night. Since your controllers in CI extend CI_Controller, you automatically inherit all the code that is contained in CI_Controller::__construct().
So for instance, if you have a controller like:
<?php class Foobar extends CI_Controller { public function index() { $this->load->view('foobar'); } }
or a model:
<?php class Foobar_model extends CI_Model { public function get_bar($limit = 1) { return $this->db->select('baz')->limit($limit) ->get('foobar')->result(); } }
There are no variables in the class you want available in every method, no matter what, so calling to the constructor is extra code to wade through, and ultimately, completely unnecessary.
Now, in a CodeIgniter Library, at times you need to grab the CI Super Object. You are usually not extending anything, so it makes total sense to call the constructor and assign get_instance() to $this->CI. Then, you have access to the CI Super Object anywhere in the class by using $this->CI.
One great usage to extend the parent constructor in a CodeIgniter Controller is if you have a application/core/MY_Controller.php file. Here you would call parent::__construct(); and put all the code you want every other controller to inherit from to have.
I hope this helps you to have a few less lines of code in your controllers and models, and illustrates that a constructor who's only purpose is to call parent::__construct(); is not needed.