0 Comments   Sunday, 10th January 2010

The Beauty of MY_Controller

 For the past few weeks, I have been attempting to re-write my CMS so as to take advantage of some of the proper features of CodeIgniter.  Having created a few projects using the framework itself, I found myself repeating a lot of code on some pages.  I had not really bothered with creating a MY_Controller file to house all the re-usable code until I started re-writing my CMS.

One of the things I wanted to save time on was authentication.  The current version of Grafik Kaos has the user authentication code slapped on every controller in the admin section.  Now that is just code I am needlessly repeating.

Basically, the code below was being copied to every single controller:

if ( ! $this->admin_model->is_logged_in())
{
    redirect('login','location');   
}

By adding the above code to a MY_Controller file, I can check authentication from one central place.

<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

class MY_Controller extends Controller {


 function MY_Controller()
 {
  parent::Controller();
  log_message('debug', 'MY_Controller Controller Initialized');
  
                // Check if user is logged in
  if ( ! $this->admin_model->is_logged_in())
  {
      redirect('login','location');  
  }

 }

}

/* End of file classname.php */
/* Location: ./system/application/controllers/classname.php */

 Now instead of accessing my base controller directly, I just access MY_Controller which will hold all the basic site code that I need.

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

 class Blog_categories extends MY_Controller 
 {
  function Blog_categories()
  {
   parent::MY_Controller();
   $this->load->model("admin_model");
  }

        // More code goes below
}

/* End of file classname.php */
/* Location: ./system/application/controllers/classname.php */

This essentially, keeps things nice and tidy.  

 
Filed In: CodeIgniter
Share |


« Previous Article Next Article »



Other Posts You Might Like


blog comments powered by Disqus

Archives

 
 

Latest Tweets

Recent Comments

Powered by Disqus

 


About Me

My name is Emmanuel Okorie. I am by profession a web designer who is trying to expand his expertise into other areas of media such as Digital Video, Photography and General Design.

You can read a bit more about me by visiting the About Me page.

 

 
[ Login ]