Reputation: 800
What is the best practice of having dynamic globals in codeigniter?
I want to load a file with constants based on what key i load from the data I tried libraries, but they are loaded before the models get initialized
How i want it to work:
1) User logs in 2) php checks if this user is a regular user (from database) or an administrator 3) if its a regular user, i will define my global variables accordingly else i will use different global variables
This should happen only once, when person logs in. And this is exactly how i do it:
The person logs in, php checks (in same controller) how the global variables need to be defined. It defines them, but as soon as i call on these variables from another controller they get erased. (I call on another controller with AJAX) Oh and i should also say that CI has bugs when we run multiple AJAX requests at the same time (you cannot use CI sessions if you use simultaneous AJAX)
SO the question really is: How do I prevent them from being erased?
Thanks
Upvotes: 0
Views: 1224
Reputation: 7398
CodeIgniter database sessions with AJAX has been solved (very recently).
My advice for you is to first extend CodeIgniter's CI_Controller
class be implementing the techniques outlined on Phil Sturgeon's blog entitled Keeping It Dry. Once this is completed, have all your controllers inherit from a MY_Controller
instead of directly from CI_Controller
.
You can then have MY_In_Controller
, MY_Out_Controller
, MY_Admin_Controller
...etc extend from MY_Controller
, but I digress. The important part is to check for logged in status in your new base controller and set the globals.
class MY_Controller extends CI_Controller{
function __construct(){
parent::__construct();
$l = $this->session->userdata("loggedin");
if((!isset($l))||($l==FALSE)){
/*user is logged out - set appropriate globals*/
}
else{
/*user is logged in - fetch them from the database and set appropriate globals*/
}
}
}
Now, when you create new controllers, say, Blog
, News
, or About
, you won't have to set the globals every time, they will be accessible in your controllers, models and views; all because the parent class will look after it.
Upvotes: 1