views:

443

answers:

4

I have written an authentication class controller containing a method to check login status of user, and redirect him to login page if he/she is not logged in.

I need to call this function from other controller methods to authenticate the user. What is a good way to do that?

+1  A: 

Take that method out of that controller.

Assuming you have a User model, that is a great place to put it if it is authenticating a user and logging them in.

Other places that you may put repeatable code is in helpers (static functions) and libraries (classes).

mrinject
A: 

Take the function to a Model or code it in a library.

Helpers I won't recommend as you are not advised to access the database from Helpers.

Easy way out is put it in a model say user_model and call it by any controller anywhere.

Geshan
A: 

I put a check login method in base controller, which is extended by all controllers. Now if a controller's action requires users to be logged in, I call it there like parent::_check_login(), if the whole controller requires it I call it from the constructor of that controller, that's all.

sumanchalki
A: 

sumanchalki is correct but he might not be giving quite enough information on how to do it.

CodeIgniter Base Classes: Keeping it DRY

This will show you how to make named base controllers such as a Admin Controller which could contain your user authentication logic and much more.

Phil Sturgeon