access the CI session in a pre controller codeigni

2019-07-18 02:48发布

问题:

I am using a pre controller hook to detect and set the site language from the session/cookie/browser lang detection.. something like this answer: Codeigniter language

I am also using the famous Tank Auth library to manage users and I am using the codeigniter Session class to store and manage the users sessions upon log in. Each user can specify the interface language he wants and store it in the database for future log ins. The lang info is copied from the DB to the session on every log in.

The problem is: I can't check the user session from inside the hook. How would I know (in case of logged in users) if his session has the lang info or not?

I am not sure if the hook approach is the best one in case of handling logged in users sessions. Let me know please if I can have a better approach.

Thanks in advance

回答1:

I solved this by using a post_controller_constructor hook instead of pre_controller. In that hook, the session is accessible. So I am setting the detected lang in the CI session AND i am loading the language file accordingly.

I am not sure if this is the best approach, but it works fine if you are not using the lang library in any controller constructor.



回答2:

use a post_controller_constructor hock. It is called after the controller constructor and before the controller method. It should do the trick for you. For me it did



回答3:

One possible solution is to try loading the session library in a CI instance from your pre-controller hook.

$CI = &get_instance();   
$CI->load->library('session');
// --- Then ---
$var = $CI->session->userdata('$the_variable_youre_checking');