Extending Controller in CodeIgniter

Posted by Nurasto | October 25, 2012 | Software and Web Development | 3 Comments

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:

  1. Create MY_Controller.php on core directory located inside application directory
  2. Create your first inherited controller class into MY_Controller.php
  3. 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

  1. keren bang tutorialnya.. 🙂

  2. SherzodKosimov says:

    Good job, signore!

  3. Aravind says:

    Great job !!!

Sorry, comments are closed

Bit and Bytes

Hello. My name is Dityo Nurasto. I am working as freelance software and web developer.

This is my personal playground. Enjoy your stay and don't hesitate to send comments.

ShoutBox