How to avoid repeating code to check if a user is logged in

First of all create your own Controller that all other controllers will inherit from.

Name it Mycontroller, for example:

defined('SYSPATH') or die('No direct script access.');
 
class Controller_Mycontroller extends Controller {
 
    public function before()
    {
        parent::before();
        //....
    }
 
} // End

Create another Cotroller “Authenticated”. This Controller must be inherited from all other controllers that should be accessed only by authenticated users.

defined('SYSPATH') or die('No direct script access.');
 
class Controller_Authenticated extends Controller_Mycontroller {
 
	public function before()
        {		
	    parent::before();
 
            if ( !Auth::instance()->logged_in('user'))
            {
                HTTP::redirect('home/index');
            }
        }
}

for example Customers page that should be accessed only from authenticated members:

defined('SYSPATH') or die('No direct script access.');
 
class Controller_Customers extends Controller_Authenticated {
    //your code
    //that's it!!
}
Categories: Kohana, PHP Tags: , , , , , ,
%d bloggers like this: