Using a super Controller class in CodeIgniter
CodeIgniter is easy to understand if you know how MVC design pattern works. Just need to define your model, your controller and your views.
However, sometimes you need to reuse code in all your site pages and probably you ask yourself “How do I do that?”.
Well, here is a simple tip that may help you to reuse generic data, fields, etc. in your CodeIgniter application.
First, I usually define my own MY_Controller class as a super class of the default Controller. You just need to create your MY_Controller.php file under application/libraries.
Then, I put there a simple $data array as a class property that will hold the data that I need to display in all my site pages.
For example, I may be interested in keeping the following variables:
$this->data['themeurl'] = $this->theme_url;
$this->data['hostname'] = $_SERVER['SERVER_NAME'];
$this->data['is_admin'] = $this->is_admin();
$this->data['is_logged_in'] = $this->dx_auth->is_logged_in();
Later, when I need to create the controller method for a given functionality, I do the following:
Imagine we are creating a Bulletin board for a web site. So I created a bulletin controller class that will handle the CRUD operations. As I mentioned before, I will make that class to extend MY_Controller. Next, in the CRUD methods, I use the following code:
function index()
{
$messages = $this->bulletin_model->get_messages();
$this->data['list'] = $messages;
$this->load->view('bulletin_list', $this->data );
}
Notice the $this->data parameter when calling $this->load->view(), instead of using $data. By doing this, I can use that multipurpose data array that was introduced in the super controller class, and loaded with default values.




That’s a smart approach! Love your articles
Ben
17 Aug 09 at 7:55 pm
Hi Ben, thank you or your comment.
Honestly I am not the original author of that idea, I just can’t remember when I learned that. Probably someone with better knowledge than me on object oriented paradigm should be the author who should win the credits …
Best.
admin
17 Aug 09 at 8:08 pm
[...] Using a Super Controller Class in CodeIgniter [...]
Using a Super Controller Class in CodeIgniter | Choose Daily
8 Sep 09 at 7:40 am
[...] That’s all, assuming that finally you will have the Country Code and Country Name under $this->data variable. You can see more info about why I use this way to pass information to view, under Using a Super Controller Class in CodeIgniter. [...]
Using GeoIP in CodeIgniter application | jigniter™
9 Jan 10 at 9:08 am