Controllers in CodeIgniter

February 20, 2009 | In: CodeIgniter

When working with controllers in CI, you always extend them from “Controller.php” such as ;

class mypage extends Controller {}

In this setup, you need to modify the core class (system/libraries/Controller.php) when you want to disable your website for maintenance or something. For me, it’s not good to modify the core files. But there is an alternative, guess what, you just have to extend it by creating another parent controller that all your suceeding pages(controllers) will inherit.

How do we do that? You will create a file named “MY_Controller.php” and put it under “libraries” folder with the following content:

class MY_Controller extends Controller {
     function __construct() {
        parent::__construct();
     }
}

Our new controller (MY_Controller.php) inherits all the properties and methods of Controller class. It’s now ready to become the new parent of all our pages.

Then we need to modify our previous “mypage” controller into :

class mypage extends MY_Controller {}

By doing this, we don’t need to edit the core Controller.php file. If we need to make our site on maintenance mode we will just add a line like below in our new class:

class MY_Controller extends Controller {
      function __construct() {
            if($under_maintenance == true) {
                echo "Site Under Maintenance";
                exit();
            }
       }

}

Hope this helps. If you have questions, just hit the comment button. 🙂



3 Responses to Controllers in CodeIgniter

Avatar

Modules in CodeIgniter» FROST : FRee and Open Source Technologies

April 30th, 2009 at 3:27 pm

[…] Controllers in CodeIgniter […]

Avatar

Senguttuvan G

July 28th, 2009 at 10:04 pm

Nice post… But it wouldn’t unfair, if had to change all my controller in existing pages? Also, how can I disable specific pages(Eg.admin pages should be always accessible whereas users should be controlled by admin by marking ‘maintenance mode’ on

Avatar

admin

July 31st, 2009 at 3:59 am

Hi Senguttuvan, thanks for the comment.
In your case, i would rather make 2 new controllers.
First controller for admin pages which is always accessible :

// Admin_Controller.php
class Admin_Controller extends Controller {}

this controller will be the parent class for the controllers in your site which are always accessible such as:

// admin_page.ph
class admin_page extends Admin_Controller {}

And another controller class for those pages that are in maintenance mode.

Comment Form