0

I need to access some functions in multiple controllers in a CodeIgniter application. At the moments the functions are really basic and a few, For example:

        generate_random_key()  //just a random string
        is_logged()           //check if user is logged or not
        logged_user_only()    //if unlogged, redirect
        unlogged_user_only() //if logged, redirect

As these functions are related to login, I can either put them in a helper file and place in Application/helpers/login_helper.php

OR

i can extend the CI_Controller, by creating MY_Controller.php and put it in Application/Core/MY_Controller.php

Both of the methods work, but I am wondering which one fits better for this kind of task. I think there should be some rules, when the Controller should be extended or when the helper should be used?

tereško
  • 58,060
  • 25
  • 98
  • 150
Roman
  • 3,764
  • 21
  • 52
  • 71

3 Answers3

1

IMO, login functionality has nothing to do with a Controller. That's the reason I would probably put the functions you mention into a helper or a library.

Alex Such
  • 471
  • 4
  • 11
1

If you're using these functions in your other controllers (and only in your other controllers) I would suggest refactoring them into MY_Controller. This would also give you direct access to the $CI instance (instead of calling get_instance())

On the other hand, you could create an Authentication library. This might be more suitable..

EDIT::

I would recommend having a MY_Controller as a base, that contains auth wrapper functions, which invoke functionality from a Library that manages this type of thing.

jlb
  • 19,090
  • 8
  • 34
  • 65
  • generate_random_key should probably stay in a helper though – jlb Jul 15 '11 at 09:01
  • yes, for example i need to check if the user is logged or not in different controllers. – Roman Jul 15 '11 at 09:03
  • I like to set up auth checking in the MY_Controller constructor. That way any controller than extends it, automatically gets an auth check. Additionally, you can set it up so that some controllers don't need it (via some access control rules, or possibly as simple as a constructor param) – jlb Jul 15 '11 at 09:06
0

The solution I m thinking:

If you want to follow design pattern, use hook(works like a filter from Java perspective).

Alternate should be extending your My_Controller

Kowser
  • 8,123
  • 7
  • 40
  • 63