0

Possible Duplicate:
Constructor session validation for different functions

Framework : CI (CodeIgniter)

Situation :

I have 4 pages(controllers) namely:

home login dashboard editprofile

ACCESS

  • home can be accessed by all types of users, logged in or not

  • login must be only be access if not authenticated

  • dashboard and editprofile must only be accessed by students(authenticated users)

I have this validatation for my controllers like this:

if($this->session->userdata('isLoggedIn')){
    // stay here do the function
} else {
// leave this page
    header('Location:'.base_url().'login');
}

I have that in my function index(){}.

But as I develop the system, as i create more methods, more controllers, it's becoming messier.. for you need to use this

if($this->session->userdata('isLoggedIn')){
// stay here do the function
} else {
// leave this page
header('Location:'.base_url().'login');
}

everytime you have a method,

i've read several questions in stackoverflow... and the only best answer is this: link here

it says that i must use decorator pattern for that... but i don't clearly get how am i suppose to do that.

Community
  • 1
  • 1
Joey Hipolito
  • 3,108
  • 11
  • 44
  • 83

1 Answers1

2

Create different base controllers for each type of user and then you only have to set that statement once. Our user controller looks like this:

<?PHP
class User_Controller extends MY_Controller
{
function __construct()
{
    parent::__construct();      
    if (!$this->session->userdata('is_logged_in')) {
        $this->session->set_flashdata('message', "I'm sorry, but you must  be logged in to view that page.");
        redirect("/");
    }
}
}

Then any controllers we want just logged in users to access extend User_Controller automatically making sure any functions are only available if you're logged in. You need to save this to the core folder to be able to extend it.

You also need to add this to your config.php to have base controllers with any prefix other than MY_

function __autoload($class)
{
if(strpos($class, 'CI_') !== 0)
{
    @include_once( APPPATH . 'core/'. $class . EXT );
}
}
Rick Calder
  • 18,310
  • 3
  • 24
  • 41