How i can use a __construct function in my other CodeIgniter controller How i can use a __construct function in my other CodeIgniter controller codeigniter codeigniter

How i can use a __construct function in my other CodeIgniter controller


Your authentication checks should be in a library:

The is an excerpt from a basic codigniter authentcation script:

class Site_sentry {    function Site_sentry()    {        $this->obj =& get_instance();    }function is_logged_in(){    if ($this->obj->session)     {        if ($this->obj->session->userdata('session_logged_in'))        {            return TRUE;        }        else        {            return FALSE;        }    }    else    {        return FALSE;    }}    function login_routine()   {     //do login here (enter into session)   }}

This library is stored in application/libraries under a filename named after its class with the .php suffix.

Then you can either add this to your autoload config file application/conig/config.php:

$autoload['libraries'] = array('database', 'site_sentry', 'session');

or load it manually in each controller:

$this->load->library('Site_sentry);

Then you can check your session from within controllers, like so:

 class Class extends Controller{    function Class()    {          parent::Controller();       if( $this->site_sentry->is_logged_in() == FALSE){            redirect('managerlogin/');        }    }   }

Also check this documentation page http://codeigniter.com/user_guide/libraries/sessions.html; of particular interest is the storing the session into the database section.


I don't think that doing it with the class is the best idea. If the user is logged in, you should check for a flag (value or whatever) inside the session, so you don't need to work with the other controller.

The advantage would be that the session can be accessed more easily and it is the more common approach.


Example with session:

class SomeClass extends Controller {function __construct(){    parent::Controller();       $this->is_logged_in();}   function is_logged_in(){    $is_logged_in = $this->session->userdata('is_logged_in');    if(!isset($is_logged_in) || $is_logged_in != TRUE)     {        redirect('login');    }}