Extending Controller in CodeIgniter
How to extend the controller on CodeIgniter? In the user guide it tells you need to extend core library and give MY_ prefix to be able to extend the controller. So, now you may start thinking “How on earth to make multiple inheritance from the core controller?”.
It’s really simple. In this case we want to have two parent/base controllers for our application controllers. The implementation flow goes like this:
- Create MY_Controller.php on core directory located inside application directory
- Create your first inherited controller class into MY_Controller.php
- Create your second inherited controller class into MY_Controller.php
Now let’s do the code. This is the sample of MY_Controller.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Base_Controller extends CI_Controller { function __construct() { parent::__construct(); //do whatever you want to do when object instantiate } } class Secure_Controller extends CI_Controller { function __construct() { parent::__construct(); $this->load->library('session'); $this->load->helper('url'); if($this->session->userdata('admin') === FALSE) { redirect('user/login', 'refresh'); } } }
Then, you can consume those controller onto your application controller. This is an example which the Admin controller inherited from Secure_Controller class. Like you know, the file name should be admin.php.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Admin extends Secure_Controller { public function index() { echo "Admin"; } }
Well, I am not really like how it done but this is the solution that I am using on CodeIgniter to make Controller multiple inheritance possible.
Comments
keren bang tutorialnya.. 🙂
Good job, signore!
Great job !!!
Sorry, comments are closed