About global variables on Codeigniter

I’m aware that global variables (that you can access throughout the whole model-view-controller thing-y) in OOP programming sounds very lazy, however I’m relatively new to Codeigniter and currently using this only as a prototype.
I’m planning to make a well structured OOP but right now I don’t have enough time to do so.
So, I’m very sorry for everyone that got “butthurt” seeing this stupid question being asked for thousand times.

Anyway, the idea is to ALWAYS show an alert of $err_msg IF this $err_msg variable is being filled, like for example $err_msg = "You don't have the permission to access this page!". And then I have a template view on my controller like this :

function view_template($current_view, $data){
    $this->load->view('header');
    $this->load->view($current_view, $data);
}
function home(){
    $this->view_template('Home','');
}

Now I’m going to show the alert on the header.php :

//keep in mind that I do change this variable according to how I use the global variable
//so if I were to use $GLOBALS['err_msg'], these $err_msg will change to $GLOBALS['err_msg']
if($err_msg != ""){
    echo '<script language="javascript">';
    echo 'alert("'.$err_msg.'")';
    echo '</script>';
    $err_msg = "";
}

I’ve been going on about a global variable that I set on constants.php for example :

$GLOBALS['err_msg'] = "";

or

define('err_msg','');

However this would only work if I call the function on my controller directly to view the page, for example :

$GLOBALS['err_msg'] = "You don't have the permission to access this page!";
$this->home();

but not

$GLOBALS['err_msg'] = "You don't have the permission to access this page!";
redirect('SomeController/home', 'refresh');

Not using redirect is going to be dangerous if it is a submit form page, because if that page is refreshed, it’s going to submit again. Not to mention that the page URL is going to be ugly.

I too tried a few methods using global variable or ordinary variable on the controller and pass it to the header, but that too won’t work if I use redirect because redirect re-calls the controller directly (sorry I can’t really explain this, but I do understand the reason why this won’t work).

Basically my controller going to check if the user that tries to access this page fulfill all the conditions to access this page. If he don’t pass, he will redirected to another page with an alert. This too sometimes apply to a submit form page, so if the user do submit but still don’t fulfill the conditions he will still be redirected.

So what do you guys think is the best way to do this? Feel free to criticize my code and sorry for my bad english.


Source: oop

Leave a Reply